← 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.
Syntax
go
for key, value := range m {
    // body
}

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
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// main is where the program starts running
func main() {
	// Short declaration: create fruitCounts and infer the type
	fruitCounts := map[string]int{"apple": 3, "banana": 5}
	// Short declaration: create total and infer the type
	total := 0
	// Loop over fruitCounts; the blank identifier _ ignores the index
	for _, count := range fruitCounts {
		total += count
	}
	// Print the values followed by a newline
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// main is where the program starts running
func main() {
	// Short declaration: create m and infer the type
	m := map[int]string{1: "a", 2: "b", 3: "c"}
	// Short declaration: create count and infer the type
	count := 0
	for k := range m {
		count++
		_ = k
	}
	// Print the values followed by a newline
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"sort"
)

// main is where the program starts running
func main() {
	// Short declaration: create scores and infer the type
	scores := map[string]int{"charlie": 3, "alice": 1, "bob": 2}
	// Short declaration: create keys and infer the type
	keys := make([]string, 0, len(scores))
	for k := range scores {
		// append adds elements and returns the updated slice
		keys = append(keys, k)
	}
	sort.Strings(keys)
	// Loop over keys; the blank identifier _ ignores the index
	for _, k := range keys {
		// Print the values followed by a newline
		fmt.Println(k, scores[k])
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.