In Go, maps are inherently unordered. When you iterate over a map using a for range loop, the iteration order is randomized. Prior to generics, developers had to write boilerplate code or type-specific functions to extract and sort map keys.
With modern Go generics and the standard library packages (cmp and slices), implementing a clean, reusable SortedKeys function is straightforward and concise.
package main
import (
"cmp"
"slices"
"fmt"
)
// SortedKeys extracts all keys from a map and returns them in sorted order.
// It works for any map where the key type is ordered (ints, floats, strings).
func SortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
slices.Sort(r)
return r
}
func main() {
// Example 1: Integer keys
intMap := map[int]string{3: "three", 1: "one", 2: "two"}
fmt.Println(SortedKeys(intMap))
// Output: [1 2 3]
// Example 2: String keys
strMap := map[string]int{"banana": 2, "apple": 4, "cherry": 1}
fmt.Println(SortedKeys(strMap))
// Output: [apple banana cherry]
}
K cmp.Ordered, V any):K cmp.Ordered restricts map keys to types that support comparison operators (<, >, <=, >=), such as integers, floats, and strings.V any allows the map values to be of any type (any is an alias for interface{}).make([]K, 0, len(m)) pre-allocates a slice with a capacity equal to the map’s length, avoiding costly dynamic memory re-allocations during the append loop.for k := range m loop collects all keys into the slice.slices.Sort(r) sorts the slice of keys in-place using Go’s highly optimized sorting algorithms.In June 2020, when Go generics were still in the design draft phase, developers had to implement custom types satisfying sort.Interface manually:
// Old pre-Go 1.18 design draft approach (Obsolete)
type Ordered interface {
type int, int8, ... // type lists in interfaces
}
type orderedSlice[T Ordered] []T
func (s orderedSlice[T]) Len() int { return len(s) }
func (s orderedSlice[T]) Less(i, j int) bool { return s[i] < s[j] }
func (s orderedSlice[T]) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
Today, modern Go provides:
cmp.Ordered (standard library since Go 1.21): Eliminates the need to define custom interface type sets for ordered types.slices.Sort (standard library since Go 1.21): Eliminates the boilerplate sort.Interface implementation (Len, Less, Swap), making slice sorting a single, readable function call.Get the curated offline edition of Kaue's Way of Lifeβa practical field guide to optimizing π Health, π° Wealth, β€οΈ Love, and π§ Meaning.
Get notified when I publish new essays, book summaries, and practical guides on living well. No spamβunsubscribe anytime.
Have a question, perspective, or suggestion? Share your thoughts below.
Updated on 2026 Oct 11.
DISCLAIMER: The content on this site is for informational and educational purposes only and does not constitute medical, psychological, financial, investment, tax, or legal advice. The ideas, curation, and opinions presented here are my own and do not represent those of my employer. Book, lecture, and article summaries are independent educational commentary and remain the intellectual property of their respective authors. AI tools may be used to assist with editing, formatting, and synthesis; while every effort is made to ensure accuracy, errors may occur. PRIVACY: This site uses third-party services for cookieless analytics (Google Analytics), optional newsletter subscriptions (Mailchimp), comments (Disqus), live chat (Tawk.to), and embedded media (YouTube), which may process visitor IP addresses and cookies in accordance with their respective privacy policies.