Maps
A map holds key value pairs and is created with make or a literal. Reading a missing key gives the zero value, so use the comma ok form to check. delete removes a key. Iteration order is random.
Example
m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
delete(m, "a")
v, ok := m["zzz"]
fmt.Println(v, ok, len(m))
if x, ok := m["b"]; ok {
fmt.Println("found", x)
}
words := []string{"go", "is", "go"}
count := make(map[string]int)
for _, w := range words {
count[w]++
}
fmt.Println(count)Result
0 false 2 found 2 map[go:2 is:1]
Exercise
Remove a key.
(m, "a")Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.