Appendix C. Zero values
Sometimes while coding, you will need the use of 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 it is given by default its zero value, which, for an integer, is 0. Note that the initialisation 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.
Most zero-values are intuitive, but there are a few that are worth keeping in mind. Those that you should absolutely remember are:
- Booleans have a zero-value
false; - Slices and maps have a zero-value equal to the
nilentity
You can find below a table of examples from the simplest to more complex types with their zero-values. Feel free to come back to this table through the book.