I’m sorry for missing a couple days. We took an long weekend with some extended family to visit the beach here in Guatemala. But I’m back, and ready to talk about … zero values!
Program initialization and execution
The zero value
When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type:
false
for booleans,0
for numeric types,""
for strings, andnil
for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
The concept of a “zero” value can be confusing to those coming from other languages that don’t have such an explicit concept.
Of course every language either requires an explicit assignment at variable declaration time or has a de facto default value. But sometimes that default value is something as nebulous as “undefined”.
Go (mostly) gives us a better experience. For most types and uses, we can simply declare a value, and start using it right away, even before we assign a value to it.
These two simple declarations are equivalent:
var i int var i int = 0
After
type T struct { i int; f float64; next *T } t := new(T)
the following holds:
t.i == 0 t.f == 0.0 t.next == nil
The same would also be true after
var t T
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)