My computer develop environment
1 | $ sw_vers |
Introduction Golang map
A Map in Go is a collection of unordered key-value pairs.
The most important point of Map is to quickly retrieve data by key. The key is similar to the index and points to the value of the data.
Maps are a collection, so we can iterate over it like iterating over arrays and slices.
However, Map is unordered, and we can’t determine its return order, because Map is implemented using a chained hash table.
So, when the map is traversed by range, the order of the keys is randomized.
1 | package main |
It can be clearly seen that the order of the keys is different each time it is traversed.
In Golang office document Go maps in action, you can find the reason.
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.
How to sort a Map?
1 | package sort |
Slice is ordered, using this feature, create a slice of the struct type for storage.
These slices will iteratively output the key-value pairs in the Map in order.