Zero Values
A declared Go variable without an explicit initializer receives its type's zero value, such as 0, false, an empty string or nil. A zero value is not necessarily ready for every operation.
Inspect the initial values of numbers, strings, pointers, slices and maps.
In some languages, a variable you forgot to set holds garbage, or crashes when you touch it. In Go, var total int is simply 0, ready to count. Knowing each type's starting value lets you skip needless setup — and spot the one case where the default bites.
The rule
Nothing is uninitialised: numbers 0, bools false, strings "", the rest nil.
| Type | Zero value |
|---|---|
int, float64, other numbers |
0 |
bool |
false |
string |
"" (empty) |
| pointers, slices, maps, channels, functions, interfaces | nil |
| arrays and structs | every element or field set to its own zero value |
var total int // 0
var longest string // ""
var verbose bool // false
var words []string // nil, len 0
var counts map[string]int // nilGo's own library leans on this. A strings.Builder or a sync.Mutex is ready to use as a plain var b strings.Builder, with no constructor call.
nil is not the same everywhere, though:
- A nil slice acts like an empty one.
len(words)is 0, you can loop over it, andappend(words, "go")allocates storage for you. - A nil map can be read —
counts["go"]returns 0 — but writing to it panics:assignment to entry in nil map. Make it first:counts := make(map[string]int). - A nil pointer panics when you follow it.