DEV Community

David Tuite
David Tuite

Posted on

3

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay