As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order.
We first create a slice of all keys, and then sort it using sort. Ints() since our map is of the form map[int]string , so the keys are integers. After that, we can iterate through the sorted slice and get the value using myMap[key] . Key: 1, Value: GoLang is Fun!
In Go, arrays and slices are data structures that consist of an ordered sequence of elements.
So, to sort the keys in a map in Golang, we can create a slice of the keys and sort it and in turn sort the slice. Firstly we will iterate over the map and append all the keys in the slice. After we have all the keys we will use the sort. String function to sort the slice alphabetically.
The Go Programming Language Specification says:
3. The iteration order over maps is not specified. [...]
That's to be expected since a map type can be implemented as a hash table, or as a search tree, or as some other data structure. But how is map
actually implemented in Go?
Put differently, what determines the iteration order of the keys in
for k, _ := range m { fmt.Println(k) }
I started wondering about this after I saw that a map with string
keys apparently do have a certain iteration order. A program like
package main
import ("fmt"; "time"; "rand")
func main() {
rand.Seed(time.Seconds())
words := [...]string{"foo", "bar", "a", "b", "c", "hello", "world",
"0", "1", "10", "100", "123"}
stringMap := make(map[string]byte)
for i := range rand.Perm(len(words)) {
stringMap[words[i]] = byte(rand.Int())
}
fmt.Print("stringMap keys:")
for k, _ := range stringMap { fmt.Print(" ", k) }
fmt.Println()
}
prints the following on my machine:
stringMap keys: a c b 100 hello foo bar 10 world 123 1 0
regardless of the insertion order.
The equivalent program with a map[byte]byte
map also prints the keys in a shuffled order, but here the key order depends on the insertion order.
How is all this implemented? Is the map
specialized for integers and for strings?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With