Maps
This is the lesson tally has been waiting for. Counting words means looking up a word and bumping its number, thousands of times. A map does that lookup in constant time, and Go's zero values make the counting line almost too short to believe.
The rule
Missing keys read as zero; make before you write; order is never promised.
A map type is written map[KeyType]ValueType. Create one with make or a literal:
counts := make(map[string]int)
stops := map[string]bool{"the": true, "a": true}The core operations:
counts["go"] = 3 // set
n := counts["go"] // get: 3
delete(counts, "go") // remove (no error if absent)
fmt.Println(len(counts)) // number of keysMissing keys read as zero. Looking up a key that is not there returns the value type's zero value, with no error. That is what makes counting one line:
for _, w := range strings.Fields("the cat saw the dog") {
counts[w]++
}
// map[cat:1 dog:1 saw:1 the:2]Make before you write. A nil map (declared with var counts map[string]int) reads fine but panics on the first write.
Order is never promised. for w, n := range counts visits every pair, but the order is unspecified and Go shuffles it between runs on purpose. For stable output, sort the keys:
for _, w := range slices.Sorted(maps.Keys(counts)) {
fmt.Println(w, counts[w])
}Two more rules:
- Keys must be comparable with
==: strings, numbers, booleans, arrays and structs of those work; slices, maps and functions do not. - Maps are shared, not copied. Assigning a map or passing it to a function hands over a reference to the same data, so a function can add to the caller's map.
The shortcut
For every map line, run three checks: made? missing key → zero? need an order → sort keys?
Made?
counts := make(map[string]int)— writable. Good.
Drills
Answer fast — trust the rule.
counts := map[string]int{}. What is counts["zebra"]?
After counting the words of "go go go stop", what is len(counts)?
Which of these is not a valid map key type?
A function addWord(m map[string]int) sets m["new"] = 1. Does the caller's map see it?
You print a map with for k, v := range m twice in one run. What can you rely on?
Remember
- Missing keys read as zero; make before you write; order is never promised.
- Shortcut: made? missing → zero? need an order → sort keys.
- Trap: nil maps panic on write, and range order changes between runs.
