Back to questions
JuniorTheoryOccasional
In what order does this loop visit the pairs of the map?
package main
import "fmt"
func main() {
m := map[int]string{1: "a", 2: "b", 3: "c"}
for k, v := range m {
fmt.Println(k, v)
}
}In no fixed order, which may differ from run to run
- Expecting
1 a,2 b,3 cbecause a run printed them so: the order is unspecified and Go randomizes it on purpose. - Expecting the sorted order of
fmt.Println(m):fmtsorts keys before printing, whilerangedoes not; sort the keys yourself.
- Why did the Go team make map iteration order random on purpose?
- How do you print a map's entries in a deterministic, sorted order?