Go docs say (强调):
Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time. A Time value can be used by multiple goroutines simultaneously.
最后一句话(关于同时在多个 goroutine 中使用时间值)是它们“通常”应该作为值而不是指针存储和传递的唯一原因吗?这对其他结构也很常见吗?我尝试在 time.Time declaration and methods 中寻找任何专门启用此功能的逻辑, 但没有注意到那里有什么特别之处。
更新:我经常需要为我的结构提供 JSON 表示形式,我宁愿省略空的/未初始化的时间。 json:",omitempty"
标记不适用于 time.Time 值,appears to be the expected behavior ,但最好的解决方法似乎是使用指针,这违背了上面引用的文档中的建议。
最佳答案
对于许多简单的值来说很常见。
在 Go 中,当某个值不大于一两个单词时,通常只是将其用作值而不是使用指针。仅仅是因为如果对象很小并且您不传递它进行更改,则没有理由使用指针。
您可能不得不忘记所有结构化的语言都不能作为值处理的实践。您可能很自然地使用整数或 float 作为值,而不是指针。为什么不多次这样做?
关于 JSON 的确切问题,假设您不想为此编写特定的 Marshaller,使用 *time.Time
没有问题。事实上这个问题已经是mentioned in the golang-nuts list .
关于pointers - 时间.时间 : pointer or value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22074077/