In Go, maps (called hashes, dictionaries, or associative arrays in other languages) are "unordered". This means that looping over a map should give each key/value pair in the map one-by-one randomly.
"When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation." - https://blog.golang.org/go-maps-in-action
One implementation is given below. However, since go lacks generics you will have to repeat this code multiple times if you use multiple types of maps.
import "sort"
var m map[int]string
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
The main reason I can think of to force the developer to maintain their own order (when needed) is performance. However, I have no idea what type of additional data structures would be needed or how much overhead this actually adds.
Are their any other reasons for a language like Go to not simply inteally keep track of the order?
