In golang is there a nice way of getting a slice of values from a map?

If I have a map m is there a better way of getting a slice of the values v than

package main
import (
  "fmt"
)

func main() {
    m := make(map[int]string)

    m[1] = "a"
    m[2] = "b"
    m[3] = "c"
    m[4] = "d"

    // Can this be done better?
    v := make([]string, len(m), len(m))
    idx := 0
    for  _, value := range m {
       v[idx] = value
       idx++
    }

    fmt.Println(v)
 }

Is there a built feature of a map? Is there a function in a Go package, or is this the best code to do if I have to?


Solution 1:

As an addition to jimt's post:

You may also use append rather than explicitly assigning the values to their indices:

m := make(map[int]string)

m[1] = "a"
m[2] = "b"
m[3] = "c"
m[4] = "d"

v := make([]string, 0, len(m))

for  _, value := range m {
   v = append(v, value)
}

Note that the length is zero (no elements present yet) but the capacity (allocated space) is initialized with the number of elements of m. This is done so append does not need to allocate memory each time the capacity of the slice v runs out.

You could also make the slice without the capacity value and let append allocate the memory for itself.

Solution 2:

Unfortunately, no. There is no builtin way to do this.

As a side note, you can omit the capacity argument in your slice creation:

v := make([]string, len(m))

The capacity is implied to be the same as the length here.