time.Time: 指针还是值

huangapple go评论96阅读模式
英文:

time.Time: pointer or value

问题

根据Go文档(已加重标记):

使用时间的程序通常应将其存储和传递为值,而不是指针。也就是说,时间变量和结构字段应该是time.Time类型,而不是*time.Time。一个Time值可以被多个goroutine同时使用。

最后一句话(关于在多个goroutine中同时使用Time值)是它们通常应该存储和传递为值而不是指针的唯一原因吗?其他结构体是否也适用这个原则?我尝试查找time.Time的声明和方法中特别启用此功能的逻辑,但没有注意到任何特殊之处。

更新:我经常需要提供结构体的JSON表示,并且我宁愿省略空/未初始化的时间。json:",omitempty"标签对于time.Time值不起作用,这似乎是预期的行为,但最好的解决方法似乎是使用指针,这与上述文档中的建议相矛盾。

英文:

The Go docs say (emphasis added):

> 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.

Is the last sentence (about using a Time value in multiple goroutines simultaneously) the only reason that they should "typically" be stored and passed as a value, rather than a pointer? Is this common to other structs as well? I tried looking for any logic that specifically enables this in the time.Time declaration and methods, but didn't notice anything special there.

Update: I often have to serve JSON representations of my structs, and I'd rather omit empty/uninitialized times. The json:",omitempty" tag doesn't work with time.Time values, which appears to be the expected behavior, but the best workaround seems to be to use a pointer, which goes against the advice in the docs quoted above.

答案1

得分: 17

对于许多简单值来说,这是很常见的。

在Go语言中,当某个值不超过一个或两个字时,通常直接将其作为值使用,而不是使用指针。这是因为如果对象很小并且不需要传递给其他函数进行修改,就没有必要使用指针。

你可能需要放弃其他语言中无法将所有结构化内容处理为值的做法。对于整数或浮点数,你可能自然而然地将它们作为值使用,而不是指针。为什么不对时间也采取同样的做法呢?

关于你在处理JSON时遇到的具体问题,并且假设你不想为此编写一个特定的编组器,使用*time.Time并没有问题。实际上,这个问题在golang-nuts邮件列表中已经提到过。

英文:

It's common for many kind of simple values.

In Go, when some value isn't bigger than one or two words, it's common to simply use it as a value instead of using a pointer. Simply because there's no reason to use a pointer if the object is small and you don't pass it to be changed.

You might have to unlearn the practice of languages where everything structured couldn't be handled as values. It's probably natural for you to use integers or floating point numbers as values, not pointers. Why not do the same for times ?

Regarding your precise problem with JSON and assuming you don't want to write a specific Marshaller just for this, there's no problem in using a *time.Time. In fact this issue was already mentioned in the golang-nuts list.

huangapple
  • 本文由 发表于 2014年2月28日 00:12:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/22074077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定