← Back to Go Course | Chapter 5: Arrays Slices Maps | Lesson 7 of 7

Iterating Over Maps

Walking through a map with range visits every key and value, but Go shuffles the order on purpose each time so you never accidentally rely on it.

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

markup
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)
}

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

markup
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)")
}

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

markup
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])
	}
}
Common Mistakes
  1. Writing code that depends on maps iterating in insertion or sorted order -- Go explicitly randomizes it each run.
  2. Trying to modify a map's keys while ranging over it, which has undefined behavior for newly added keys.
  3. Forgetting to sort keys explicitly (e.g. via a separate slice) when a deterministic, repeatable output order is actually required.
Chapter Summary
  • '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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.