HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Getting a slice of keys from a map

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromslicekeysgettingmap

Problem

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.

Code Snippets

package main

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

Context

Stack Overflow Q#21362950, score: 315

Revisions (0)

No revisions yet.