Understand the contract
Sorting gives a collection an explicit order. The sort package includes helpers for strings and integers, and slices.Sort is another option in modern Go. A map has no guaranteed iteration order, so collect its keys and sort them before generating output whose order needs to stay predictable.
The key slice is independent of the map structure, but the values are still read from the map after sorting. Do not mutate the map concurrently. Sorting a slice modifies its element order in place; copy the slice first if callers still need its original ordering.
Work through the example
The example reserves enough capacity for all keys, appends each key and sorts them lexicographically. It then prints api 3 before go 2. This pattern is useful for small reports and deterministic tests, where unspecified map ordering would otherwise make results difficult to compare.
package main
import (
"fmt"
"sort"
)
func main() {
counts := map[string]int{"go": 2, "api": 3}
keys := make([]string, 0, len(counts))
for key := range counts { keys = append(keys, key) }
sort.Strings(keys)
for _, key := range keys { fmt.Println(key, counts[key]) }
}Watch this boundary
For custom comparisons, define a consistent ordering. Using <= instead of < for a less function can violate the required strict ordering when values are equal. Also distinguish byte-oriented string ordering from a human language’s collation rules; basic string sorting does not implement locale-aware dictionary order.
Practice with a changed input
Add another key and verify the output order. Then sort a slice of scores in descending order, including duplicates, and check that equal values remain valid inputs.
Lesson 19 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services