Iterating Over Maps
Start with Iterating Over Maps
A range loop visits map keys and values, but Go deliberately leaves their iteration order unspecified. Code must not depend on a particular visit order.
What you’ll learn
- Explain the main purpose of iterating over maps.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use for key, value := range m when order is irrelevant. For deterministic output, collect keys into a slice, sort the keys and then retrieve their values from the map in sorted order.
This matters in tests, examples and reports: printing a map directly or ranging over it may show items in different orders. Sorting keys is an explicit application choice; the map itself remains unordered.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"sort"
)
func main() {
ages := map[string]int{"Zoe": 10, "Ava": 12, "Mia": 11}
keys := make([]string, 0, len(ages))
for key := range ages {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(key, ages[key])
}
}
Output
Ava 12
Mia 11
Zoe 10Trace what the program does
The first loop gathers all three keys without assuming their order. Sorting places them alphabetically as Ava, Mia and Zoe. The second loop looks up each score and prints a predictable sequence, making the example suitable for tests.
Avoid common mistakes
- Do not expect for range over a map to follow insertion or alphabetical order.
- If stable presentation is required, sort a collection of keys explicitly.
Try it yourself
Add the key "Ben" with age 9 and confirm the sorted output now places it between Ava and Mia.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Iterating Over Maps in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.