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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With