Iterating Over Maps
Basic Map Iteration
range over a map yields each key and its corresponding value, letting you process every entry without needing to know the keys in advance.
Example: Basic Map Iteration
package main
import "fmt"
func main() {
fruitCounts := map[string]int{"apple": 3, "banana": 5}
total := 0
for _, count := range fruitCounts {
total += count
}
fmt.Println("total fruit:", total)
}
Login to try C/C++/Java/PHP code in the editor
Iteration Order Is Randomized
Go deliberately randomizes the order in which range visits a map's entries, on every single run of the program. This is intentional, to stop developers from accidentally depending on an order that was never guaranteed.
Note: Never write code (or tests) that assume a particular map iteration order.
Example: Iteration Order Is Randomized
package main
import "fmt"
func main() {
m := map[int]string{1: "a", 2: "b", 3: "c"}
count := 0
for k := range m {
count++
_ = k
}
fmt.Println("visited", count, "entries (order varies each run)")
}
Login to try C/C++/Java/PHP code in the editor
Getting a Deterministic Order
When a stable, repeatable order matters -- like printing a report -- collect the map's keys into a slice, sort that slice, and then look up each value through the sorted keys.
Example: Getting a Deterministic Order
package main
import (
"fmt"
"sort"
)
func main() {
scores := map[string]int{"charlie": 3, "alice": 1, "bob": 2}
keys := make([]string, 0, len(scores))
for k := range scores {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, scores[k])
}
}
Login to try C/C++/Java/PHP code in the editor
- Writing code that depends on maps iterating in insertion or sorted order -- Go explicitly randomizes it each run.
- Trying to modify a map's keys while ranging over it, which has undefined behavior for newly added keys.
- Forgetting to sort keys explicitly (e.g. via a separate slice) when a deterministic, repeatable output order is actually required.
- 'for key, value := range m' iterates over every entry in a map.
- Map iteration order is randomized by the Go runtime and must never be relied upon.
- To get a predictable order, collect the keys into a slice and sort that slice first.
- Deleting the current key during iteration is safe; adding new keys during iteration has undefined effects.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: