Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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?

like image 677
masebase Avatar asked Nov 16 '12 18:11

masebase


People also ask

How do I get map values in Go?

You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you'll get the assigned value. Otherwise, you'll get the zero value of the map's value type.

What are slices in Golang?

Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array.

How do I append to a slice in Golang?

Since slices are dynamically-sized, you can append elements to a slice using Golang's built-in append method. The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.


2 Answers

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.

like image 164
nemo Avatar answered Sep 26 '22 00:09

nemo


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.

like image 28
jimt Avatar answered Sep 25 '22 00:09

jimt