All of the answers here now contain the old behavior of maps. In Go 1.12+, you can just print a map value and it will be sorted by key automatically. This has been added because it allows the testing of map values easily.
func main() {
m := map[int]int{3: 5, 2: 4, 1: 3}
fmt.Println(m)
// In Go 1.12+
// Output: map[1:3 2:4 3:5]
// Before Go 1.12 (the order was undefined)
// map[3:5 2:4 1:3]
}
Maps are now printed in key-sorted order to ease testing. The ordering rules are:
- When applicable, nil compares low
- ints, floats, and strings order by <
- NaN compares less than non-NaN floats
- bool compares false before true
- Complex compares real, then imaginary
- Pointers compare by machine address
- Channel values compare by machine address
- Structs compare each field in turn
- Arrays compare each element in turn
- Interface values compare first by reflect.Type describing the concrete type and then by concrete value as described in the previous rules.
When printing maps, non-reflexive key values like NaN were previously displayed as
<nil>
. As of this release, the correct values are printed.
Read more here.