Code Snippets
/

Iterating a Map in Go

Iterating a Map in Go

Maps in Go are unordered: each program run randomises the iteration order to discourage code that relies on it. This snippet shows the basic `for key, value := range m` form, the comma-ok idiom for safe lookup, and the canonical pattern for iterating in sorted order. Internalise these three and you avoid the most common map bugs.

Go
Easy
3 snippets
go-maps
data-structures
iteration-patterns

1,193 views

21

package main

import (
    "fmt"
    "sort"
)

func main() {
    ages := map[string]int{
        "ada":      36,
        "linus":    54,
        "margaret": 88,
    }

    // Order is randomised each run; do NOT rely on it.
    for name, age := range ages {
        fmt.Printf("%s = %d\n", name, age)
    }

    // Key-only:
    for k := range ages {
        _ = k
    }

    fmt.Println("size =", len(ages))
    _ = sort.Strings // keep import alive; used in the next accordion
}

for k, v := range m iterates over key/value pairs; drop , v if you only want keys, drop k, if you only want values (or use for _, v := range m). The runtime deliberately randomises the order each iteration to keep maps a black box, so any code that depends on order is buggy by definition. len(m) is O(1) and reports the current number of entries. Modifying the map during iteration is allowed but visiting newly added keys is unspecified; deleting the current key is safe.