Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time.Time: pointer or value

Tags:

pointers

time

go

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.

like image 549
Mzzzzzz Avatar asked Feb 27 '14 16:02

Mzzzzzz


Video Answer


1 Answers

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.

like image 62
Denys Séguret Avatar answered Sep 27 '22 19:09

Denys Séguret