In Go, map contents are randomized. Go doesn’t care about insertion order. Elements in a map are always random when iterating through them.
To iterate through map contents in insertion order, we need to create a slice that keeps track of each key. Then we iterate through this slice and use its contents (which are the map keys) to access the map’s values in the order in which they were inserted:
| |
$ go run example.go
Key: a Value: 0
Key: b Value: 1
Key: c Value: 2
Key: d Value: 3
Key: e Value: 4
Key: f Value: 5
Now each key and value is printed in insertion order.
Additional Notes
The following example shows how iterating through a map won’t print out values in order even if assignment was done in a certain order:
| |
And the output is:
$ go run example.go
Key: e Value: 4
Key: f Value: 5
Key: a Value: 0
Key: b Value: 1
Key: c Value: 2
Key: d Value: 3
Interestingly, printing a map with fmt.Println prints elements in key-sorted order and NOT by insertion order. Since Go 1.12, the fmt package sorts map keys for display purposes:
| |
$ go run example.go
map[a:0 b:1 c:2 d:3 e:4 f:5]
The keys were inserted in a random order, but printing the map displays the key-value pairs sorted by key (alphabetically).