๐Ÿ”‘ Get Sorted Keys From Map in Go Using Generics ๐Ÿ”—

Get Sorted Keys From Map in Go Using GenericsGet Sorted Keys From Map in Go Using Generics

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.

๐Ÿ“‘ Table of Contents ๐Ÿ”—


๐Ÿ’ป The Modern Implementation (Go 1.21+) ๐Ÿ”—

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]
}

โš™๏ธ How It Works ๐Ÿ”—

  1. Generic Type Constraints (K cmp.Ordered, V any):
  2. Pre-allocating the Slice:
  3. Extracting Keys:
  4. Sorting:

๐Ÿš€ Why This Version is Better Than the 2020 Draft ๐Ÿ”—

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:


๐Ÿ“š Download My Free Ebook ๐Ÿ”—

Get the curated offline edition of Kaue's Way of Lifeโ€”a practical field guide to optimizing ๐Ÿ Health, ๐Ÿ’ฐ Wealth, โค๏ธ Love, and ๐Ÿง˜ Meaning.

Kaue's Way of Life

Kaue's Way of Life

๐Ÿ’ฌ Comments & Discussion ๐Ÿ”—

Have a question, perspective, or suggestion? Share your thoughts below. Comments are powered by GitHub Discussions (ad-free and spam-free)โ€”click Sign in with GitHub below to comment or react (creating a free GitHub account takes less than a minute).



Updated on Oct 11, 2026.

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 comments (giscus / GitHub Discussions) and embedded media (YouTube), which may process visitor IP addresses and cookies in accordance with their respective privacy policies.