Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

How to Get a Slice of Map Keys in Go

1 min read .
How to Get a Slice of Map Keys in Go

Go maps store key-value pairs, but many tasks only need the keys—for example, to sort them, display them, compare sets, or feed them into another operation.

Map iteration is intentionally unordered, so extracting keys into a slice is also the first step when you need a deterministic order.

1. Collect All Keys with range

func getMapKeys(m map[string]int) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	return keys
}

func main() {
	myMap := map[string]int{
		"apple":  1,
		"banana": 2,
		"cherry": 3,
	}

	keys := getMapKeys(myMap)
	fmt.Println("Keys:", keys)
}

Preallocating the slice with capacity len(m) avoids unnecessary growth while keys are appended.

Do not rely on the order returned by map iteration. Go deliberately does not guarantee it.

2. Sort String Keys

If you need stable lexical ordering:

import "sort"

func getSortedMapKeys(m map[string]int) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}

	sort.Strings(keys)
	return keys
}

Example:

myMap := map[string]int{
	"banana": 2,
	"apple":  1,
	"cherry": 3,
}

keys := getSortedMapKeys(myMap)
fmt.Println("Sorted Keys:", keys) // [apple banana cherry]

In modern Go, the slices package also provides generic sorting helpers.

3. Generic Key Extraction

With Go generics, one helper can work for any comparable key type:

func mapKeys[K comparable, V any](m map[K]V) []K {
	keys := make([]K, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	return keys
}

Example:

numbers := map[int]string{
	10: "ten",
	20: "twenty",
}

keys := mapKeys(numbers)
fmt.Println(keys)

The result order is still unspecified unless you sort it afterward.

4. Custom Struct Keys

A struct can be a map key when all of its fields are comparable:

type Person struct {
	Name string
	Age  int
}

func getPersonKeys(m map[Person]int) []Person {
	keys := make([]Person, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}

	sort.Slice(keys, func(i, j int) bool {
		return keys[i].Name < keys[j].Name
	})

	return keys
}

You can sort by Name, Age, or another rule depending on the application’s needs.

Conclusion

To get map keys in Go, range over the map and append each key to a slice. Preallocate when you know the final size, sort the resulting slice whenever deterministic order matters, and use a generic helper if the same operation appears across multiple key and value types.

Related Posts

chevron-up