Search code examples
dictionarygoslice

In Go how to get 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 this?

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-in feature of a map? Is there a function in a Go package, or is this the only way to do this?


Solution

  • 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.