4
One Slice can vary with the need and can add items to it, right? It is possible to view the size and its capacity (len
and cap
, respectively).
In the tour by Go, there is a "lesson" from append, first he creates a Slice null and then add a 0 to it and size becomes 1 and capacity becomes 2. At last append
, he adds "2, 3, 4" to Slice which already had 2 of size and 2 of capacity, and gets size of 5 capacity of 8.
How the capacity of Slices in Go? How is the "growth" of Slices?
Here is the code:
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
printSlice(s[:0])
// Extend its length
printSlice(s[:4])
// Drop its first two values.
printSlice(s[2:])
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
"It doubles the capacity" It’s not quite so. The way the
slice
grows depends so much on the capacity of theslice
how many elements will be added. For those who are curious, here is the function that coordinates Slice growth.– Felipe Marinho
@Felipemarinho is, I don’t remember if I got confused, or was like that and already changed. I was going to say that this is implementation detail and forgot, thank you.
– Maniero