time.Time:指针或值 [英] time.Time: pointer or value

查看:102
本文介绍了time.Time:指针或值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听文档说(强调):

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

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.Time声明和方法,但没有发现任何特别之处.

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.

更新:我经常必须提供结构的JSON表示形式,而宁愿省略空/未初始化的时间. json:",omitempty"标记不适用于time.Time值,它会显示 ,但是最好的解决方法似乎是使用一个指针,该指针与上面引用的文档中的建议背道而驰.

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.

推荐答案

对于许多简单值来说很常见.

It's common for many kind of simple values.

在Go中,当某些值不超过一两个单词时,通常简单地将其用作值而不是使用指针.仅仅是因为如果对象很小并且没有传递它进行更改就没有理由使用指针.

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 ?

关于JSON的确切问题,并假设您不想为此编写特定的Marshaller,使用*time.Time没问题.实际上,这个问题已经在golang-nuts列表中中提到

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.

这篇关于time.Time:指针或值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆