Iterate without depending on order
Iterate without depending on order
Use for key, value := range m to visit entries. Iteration order is unspecified and may differ between traversals. Aggregate values or explicitly order the keys when output must be stable.
package main
import "fmt"
func main() { m := map[string]int{"tea": 3, "rice": 5, "bread": 2} total := 0 for _, v := range m { total += v } fmt.Println(total)}The sum is independent of traversal order. Use for k := range m when only keys are needed. Do not infer the order of range from how fmt displays a map.
Expected output:
10Collect and sort keys
package main
import "fmt"import "sort"
func main() { m := map[string]int{"tea": 3, "rice": 5, "bread": 2} keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Println(k, m[k]) }}The sort package orders the key slice in ascending string order, not locale-specific collation. The map remains unordered. In one goroutine, a not-yet-visited deleted entry is skipped; a newly inserted entry may or may not be visited. Prefer separate mutation and traversal phases.
Expected output:
bread 2rice 5tea 3Try it locally
Given map[string]int{"z":2,"a":1,"m":3}, collect keys, sort with sort.Strings, then print key and value on each line.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 06: Iterate without depending on order
Check the lesson objective before moving on.
What order does map range guarantee?
How can you print string keys in ascending order?