Module lessons (3/5)
Maps: keys and values
A map is a key→value hash table: map[K]V. Maps are reference
types: passed to a function, they share the same storage. They must be
initialized before you can write to them (with make or a literal).
Creation
// with a literal
prices := map[string]int{"pane": 2, "latte": 3}
// with make
counters := make(map[string]int)
counters["a"] = 1
// nil map (readable, NOT writable)
var m map[string]int
fmt.Println(m["x"]) // 0 — ok
// m["y"] = 1 // PANICBasic operations
m := map[string]int{"a": 1}
m["b"] = 2 // insert/update
v := m["a"] // get; if missing: zero value
delete(m, "a") // remove (ok even if the key doesn't exist)
n := len(m) // number of entriesComma-ok: distinguishing "missing" from "zero value"
v, ok := m["x"]
if !ok {
fmt.Println("key missing")
} else {
fmt.Println("found:", v)
}It's the only way to know whether a key exists, because m["x"] returns
the zero value even when the key isn't there. A fundamental pattern.
Iteration: randomized order
for k, v := range m {
fmt.Println(k, v)
}Keys: only comparable types
Keys must be comparable: string, numbers, bool, pointers,
channels, interfaces, arrays of comparable types, structs of comparable
fields. Slices, maps and functions are not comparable → they cannot
be keys.
m := map[[2]int]string{} // ok: array is comparable
// m := map[[]int]string{} // ERROR: slice is not comparablePattern: counters
One of the most common uses of maps:
words := []string{"a", "b", "a", "c", "b", "a"}
freq := map[string]int{}
for _, w := range words {
freq[w]++ // access to a missing key is 0 → 0+1 = 1
}
// freq = {"a": 3, "b": 2, "c": 1}Try it
Create a map[string]int with values 'a' -> 1 and 'b' -> 2, then add 'c' -> 3.
Show hint
Literal: `map[K]V{"key": value, ...}`.
Solution available after 3 attempts
Use the comma-ok pattern to read the key 'x' (not present) into v, ok and print both.
Show hint
Two return values: the value and a presence boolean.
Solution available after 3 attempts
What happens when writing to a nil map?
var m map[string]int
m["a"] = 1Recap
map[K]V: key-value, reference, hash-backed.- Initialize with
makeor a literal; nil map → panic on write. v, ok := m[k]is the only way to distinguish "missing" from "zero value".delete(m, k)removes; ok even ifkdoesn't exist.rangeiteration: randomized order.- Keys: only comparable types (no slice/map/func).
- Counters pattern:
freq[k]++leverages the implicit zero value.