Zero Values
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.
The shortcut
For any variable, ask "what would the empty version of this be?" — zero, false, blank, or nothing. Then ask one follow-up only for maps and pointers: "am I about to write through a nil?"
The total
var total intis 0.total++gives 1. No setup needed.
Once the map exists, the zero value becomes a gift: a missing key reads as 0, so counts[w]++ both creates the entry and increments it.
Drills
Answer fast — trust the rule.
What does var ready bool hold before any assignment?
After var name string, what does len(name) return?
What happens with var tags []string followed by tags = append(tags, "go")?
What happens with var seen map[string]bool then seen["go"] = true?
Given var p struct{ Word string; Count int }, what is p.Count?
Remember
- Nothing is uninitialised: numbers 0, bools false, strings "", the rest nil.
- Shortcut: ask "what is the empty version?", then "am I writing through a nil?"
- Trap: nil slices are safe to append to; nil maps panic on write.
