What is the 'Zero Value' in Go, and why is it useful?
Last updated
The zero value is the default value Go automatically assigns to any variable declared without an explicit initializer, so every variable is always usable and there is no concept of uninitialized memory.
Defaults by type:
0for numeric types,falseforbool,""for strings.nilfor pointers, slices, maps, channels, functions, and interfaces.For structs, every field is recursively set to its own zero value.
Why it's useful:
No uninitialized-variable bugs: declaring is always safe.
Enables 'useful zero values': a type works out of the box without a constructor (e.g.
sync.Mutex,bytes.Buffer, andstrings.Builderare ready to use when zero).
Caveats:
A nil map can be read but panics on write; you must
makeit first.You sometimes can't distinguish 'set to zero' from 'never set' (use a pointer or ok-flag if that matters).
- https://www.geeksforgeeks.org/go-language/zero-value-in-golang/
- https://www.geeksforgeeks.org/go-language/time-durations-in-golang/
- https://www.freecodecamp.org/news/variables-and-constants-in-go/
- https://www.freecodecamp.org/news/build-an-lsm-tree-storage-engine-from-scratch-handbook/
- https://stackoverflow.com/questions/31581867/is-it-required-to-assign-default-value-to-variable