Lesson 7: Maps¶
Big Picture¶
flowchart LR
K["key (hashable)"] -->|hash function| B["bucket"]
B --> V["value"]
subgraph "map[string]int"
B1["'one'"] --> V1["1"]
B2["'two'"] --> V2["2"]
end
Q["v, ok := m['k']"] -->|"ok == false"| Z["zero value,<br/>NOT an error"]
Two idioms to memorize: make(map[K]V) (a nil map panics on write!) and the comma-ok pattern v, ok := m[k] to tell "absent" apart from "zero value".
Concepts¶
Creating Maps¶
Operations¶
Check Key Exists¶
Iteration¶
Code Walkthrough¶
Full program: code/07_maps.go.
Exercises
- Write a word-frequency counter:
map[string]intover a slice of strings. - Try writing to a
var m map[string]intwithoutmake— what happens? - Build a nested map
map[string]map[string]int(e.g., city → metric → value).
Check Your Understanding¶
#
v := m["missing"] on a map[string]int — what is v?
#
How do you check if key "k" exists in map m?