Slices, maps and strings · 3 MIN READ
Map iteration order is not specified
Produce stable output from a map without hoping.
The language does not specify map iteration order, and the order may change from one iteration to the next. A small example that repeatedly uses one order does not establish a guarantee.
When output must be deterministic, collect the keys, sort them and read values in that sorted order. When order is irrelevant, test the entries without requiring a particular traversal sequence.
SEE THE IDEA
Sort keys when output order matters
- 01
Map
gomap[string]intStores associations, not an order
- 02
Collect
gokeys = append(keys, key)Extract the keys
- 03
Sort then read
goslices.Sort(keys)Produce deterministic output
The language does not specify map iteration order.
In practice
Use sorted keys for reports, snapshots, stable tests and serialized text. Test membership independently of order when order is irrelevant. An iteration may use a different order on the next pass; seeing one repeated order in a small example does not establish a guarantee.
Watch out
Do not describe map traversal as insertion order or rely on a particular random distribution.
Work through the exercise
package main
// SortedKeys returns the map's keys in ascending order.
func SortedKeys(m map[string]int) []string {
return nil
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.