🔑 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:



💬 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 no tracking cookies; browser local storage is used solely to remember optional language and playback-speed preferences, and hosting logs on Google Cloud process visitor IP addresses, browser metadata, requested resources, page engagement, and referral sources for aggregate traffic statistics. Third-party services used for optional newsletter subscriptions (Mailchimp), comments (giscus / GitHub Discussions), and media downloads/streaming (GitHub) may process visitor IP addresses and cookies in accordance with their respective privacy policies.