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

In Go how to get a slice of values from a map?

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

Problem

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.

Code Snippets

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

Context

Stack Overflow Q#13422578, score: 82

Revisions (0)

No revisions yet.