Home >Backend Development >Golang >How to Iterate Through Go Maps in a Specific Order?
Why Maps Print Out of Order
In Go, maps are unordered collections of key-value pairs. This means that the order of elements in a map is not guaranteed. When you iterate over a map, the elements are returned in an arbitrary order, which can be confusing or problematic if you require a specific order.
Getting Maps in Order
To get maps in order, you can use the sort package. Here's an example:
package main import ( "fmt" "sort" ) type monthsType struct { no int text string } var months = map[int]string{ 1:"January", 2:"Fabruary", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"Novenber", 12:"December", } func main(){ // Create a slice of the map keys keys := make([]int, len(months)) i := 0 for key := range months { keys[i] = key i++ } // Sort the slice of keys sort.Ints(keys) // Iterate over the keys and print the corresponding values for _, key := range keys { fmt.Println(key, "-", months[key]) } }
This code will output the map elements in ascending order of the keys:
1 - January 2 - Fabruary 3 - March 4 - April 5 - May 6 - June 7 - July 8 - August 9 - September 10 - October 11 - Novenber 12 - December
The above is the detailed content of How to Iterate Through Go Maps in a Specific Order?. For more information, please follow other related articles on the PHP Chinese website!