liveBook · Manning

Iteration order

As explained in 100 Go Mistakes and How to Avoid Them

Map iteration order is the sequence in which elements of a Go map are produced during iteration, which is not deterministic or insertion-preserving.

Do not treat Go map iteration as sorted, insertion-preserving, storage-order, or repeatable. A range loop may produce different key sequences across iterations. section 4.4.1

for k := range m {
    fmt.Print(k)
}

This range loop exposes the mistake: printing map keys does not establish a stable order. section 4.4.1

The same loop can print different sequences

Running the key-printing loop twice can produce outputs such as `zdyaec` and `czyade`. The specification calls the distribution unspecified rather than uniformly random, so neither sequence should drive program logic. section 4.4.1

Avoid relying on these map-iteration properties:

Updating a map while ranging

Adding entries to the map being ranged can produce different final maps. Copy the original map first, then iterate over the original while applying updates to the copy when predictable, repeatable output is required.

When ordering is required, use another data structure or an ordering-aware operation. JSON marshaling may alphabetize map keys, but that behavior belongs to the marshaling package, not to maps themselves. section 4.4.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains unspecified and nonuniform iteration, demonstrates varying outputs, and gives a copy-before-update technique.
Examples
Uses key-printing loops, contrasting key sequences, and map-copy examples that isolate updates from iteration.
What it assumes
Assumes familiarity with Go maps and range loops.
What you can do after
Diagnose ordering assumptions and apply map copies or alternative structures when output must be predictable.
How it connects
Connects Go maps with range loops, insertion order, sorted order, JSON marshaling, and alternative data structures.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.