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:
- Keys appear in sorted order. section 4.4.1
- Keys retain insertion order. section 4.4.1
- Each iteration produces the same sequence. section 4.4.1
- An entry added during iteration is necessarily visited during that iteration. section 4.4.2
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
