14

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.

Mzzzzzz
  • 4,770
  • 7
  • 30
  • 47

1 Answers1

17

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Good points. One reason I asked is that I often have to serve JSON representations of my structs, and I'd rather omit empty/uninitialized times. Since the `json:",omitempty"` tag doesn't work with time.Time values, I've been using pointers. I'll update my question to mention this. – Mzzzzzz Feb 27 '14 at 16:24
  • 1
    In your case, if you need to prevent null times from being dumped in JSON and you don't want to override the marshaller, then I see no real problem in using a pointer. – Denys Séguret Feb 27 '14 at 16:34