I'm appending the values of a map into an existing slice.
The code's like (the s
is a slice that already has some elements in it):
for key, value := range m {
s = append(s, value)
}
As far as I know, slices in Go double their sizes when needed. I could let it double the capacity of itself, but it'll happen several times a loop, which probably is bad for performance.
In this case, I know the exact space needed, that is, len(m)
. How do I “reserve” the space for a slice, like that in C++? I want the reallocation to happen just once.
You allocate memory for an object with make
, like ( play ):
s := make([]string, len(m))
for i, v := range m {
s[i] = v
}
Alternatively, you can create a slice of length zero, but with enough capacity to hold n values. Here, append will never need to be allocate new memory, if the number of items appended does not exceed capacity ( play ).
s := make([]string, 0, len(m))
for _, v := range m {
s = append(s, v)
}
If you like to dive into slices more visually, this blog post may help:
If you want to manually enlarge an slices with element you would need to:
copy
to copy elements overExample on play .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.