Learning Bits

Null vs Zero value in Go

Last week there was an interesting question that popped while writing code?

How Zero Value and null value are seen in Go? When to use pointers to variables to get nil?

Go has the concept of zero value which indicates the default value for any declared variable without explicit value, as the go spec explains it is based on the variable type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. It's done recursively following the same type rules.

Although the commonly null used to indicate no-value, nil, is available in Go, it isn't the zero value for strings and some other types, what happens in domains where false, 0 and "" are a valid value and can't be used to differentiate no-value.

It becomes interesting, nuanced, an option is to use a pointer and get nil, although it comes with the caveat of mutability and nil checks. When using functions the coma ok idiom is preferred (value, ok := ), then a question rise: what happens if the function can also return an error? And then there is JSON marshaling and unmarshaling.

And those questions are other learning bits.

Sources for this bit:

  1. zero value @ Go spec
  2. Learning Go, 2nd Edition By Jon Bodner
  3. Learning Go By Jon Bodner
  4. Ultimate Go: Advanced Concepts By William Kennedy