DEV Community

David Tuite
David Tuite

Posted on

Time Zero Values in Golang

#go

Golang has a concept of zero values and functions will sometimes return their zero value.

This reminds me of Ruby where it is common (and some might say, problematic) for methods to return nil.

return nil unless something == "everything"
Enter fullscreen mode Exit fullscreen mode

That's why you have the safe-check operator in Ruby. It eases the pain of checking for nil all over the place.

account&.owner&.address
Enter fullscreen mode Exit fullscreen mode

Go, of course, is typed. If a function is supposed to return a string then it can't just bang in a nil instead because there isn't a meaningful string to return.

So what do they do instead?

Well, each type has it's own "zero value". The zero value for string is "", the zero value for int is 0 and the zero value for error is actually, nil.

By what about time? What does it mean to have zero time? Is that the start of the big bang? 💥

If you want to return "nil Time" in Go, you should return time.Time{}.

Oddly, you don't seem to be able to do myTime != time.Time{} to check if a time is zero. Instead the thing to do seems to be myTime.isZero().

Great!

Top comments (0)