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.
Let’s say we have a map of the first and last names of language designers. We want to print first and last names in sorted order by their first name.
We need to perform the following:
package main import ( "fmt" "sort" ) func main() { designedBy := map[string]string { "Robert": "Griesemer", "Rob" : "Pike", "Ken": "Thompson", } // create slice and store keys firstNames := make([]string, 0, len(designedBy)) for k := range designedBy { firstNames = append(firstNames, k) } // sort the slice by keys sort.Strings(firstNames) // iterate by sorted keys for i, firstName := range firstNames { fmt.Println(i+1, firstName, designedBy[firstName]) } }
In Go version 1.12 and later, maps are printed in key-sorted order to ease testing.
RELATED TAGS
CONTRIBUTOR
View all Courses