pointers - 时间.时间 : pointer or value

标签 pointers time go

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/

相关文章:

c - 使用三重指针将内存分配给 3D 数组

cocoa - 为什么我的 Macruby 指针无法作为 void 指针传递?

go - 如何部署放置在子包中的 Go Google Cloud 函数?

amazon-web-services - 无法使用AWS CodePipeline构建和部署Go Lambda-BundleType必须为YAML或JSON

c - C 中动态堆栈的不兼容指针类型问题的赋值

c - 每三次运行我的程序时出现段错误,使用 malloc

winapi - 如何在 C++ 中使用 LoadLibrary(..) 调用 kernel32.dll 函数 GetTickCount()

performance - 如何将准确度绘制为 Keras 中处理时间的函数?

arrays - 根据月份确定冬季或夏季时间(UTC 时区)

struct - 在已经类型化的结构上进行 Go 结构类型