Search code examples
dictionarygoslice

Getting a slice of keys from a map


Is there any simpler/nicer way of getting a slice of keys from a map in Go?

Currently I am iterating over the map and copying the keys to a slice:

i := 0
keys := make([]int, len(mymap))
for k := range mymap {
    keys[i] = k
    i++
}

Solution

  • For example,

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

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