C.1 What is a zero value?
Sometimes while coding, you’ll need to use a variable without assigning a value. For example, a variable should be declared before a condition to exist outside of it:
var counter int if readline(&buf) { counter += 1 } fmt.Println(counter)
In this case, the variable counter
is declared without an explicit initial value, meaning counter
is given its zero value by default, which, for an integer, is 0
. Note that the initialization to zero value is done recursively either for a slice
, a map
, or a structure: each element or field will be set to its zero value according to its type.
C.2 The zero values of any types
Most zero values are intuitive, but a few are worth keeping in mind. Those that you should absolutely remember are listed here:
- Booleans have a zero value of
false
. Slice
s andmap
s have a zero value equal to thenil
entity.
Table C.1 shows examples from the simplest to the more complex types with their zero values. Feel free to come back to this table throughout the book.