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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With