How to Get a Slice of Keys from a Map in Go

Created
Modified

Using For Range

The easiest way to get keys of map in Golang:

package main

import "fmt"

func main() {
  m := map[string]int{
    "a": 1,
    "b": 1,
    "c": 1,
  }

  // minimize memory allocations
  keys := make([]string, 0, len(m))
  for k := range m {
    keys = append(keys, k)
  }
  fmt.Printf("%q\n", keys)
}
["c" "a" "b"]

To be efficient in Go, it's important to minimize memory allocations.

Using maps.Keys Function

Keys returns the keys of the map m. The keys will be in an indeterminate order.

Go now has generics starting with version 1.18. We can get the keys of any map with maps.Keys. The following example:

// version 1.18+
package main

import (
  "fmt"

  "golang.org/x/exp/maps"
)

func main() {
  m := map[string]int{
    "a": 1,
    "b": 1,
    "c": 1,
  }

  // using 1.18 or later
  keys := maps.Keys(m)
  fmt.Printf("%q\n", keys)
}
["c" "a" "b"]

maps package is found in golang.org/x/exp/maps. This is experimental and outside of Go compatibility guarantee. They aim to move it into the std lib in Go 1.19.

Using reflect Package

You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

package main

import (
  "fmt"
  "reflect"
)

func main() {
  m := map[string]int{
    "a": 1,
    "b": 1,
    "c": 1,
  }

  keys := reflect.ValueOf(m).MapKeys()
  fmt.Printf("%q\n", keys)
}
["b" "c" "a"]

Related Tags

#get# #slice# #keys#