A slice can vary with need, and you can add items to it, right? You can view the size and its capacity ( len
and cap
, respectively).
On the tour by Go, there is a "lesson" from append , it first creates a slice null and then adds a 0 to it and the size becomes 1 and the capacity becomes 2. In the last append
, it adds "2, 3, 4" to slice which already had 2 size and 2 capacity, and gets 5 capacity size of 8.
How does the ability of slices in Go? What 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)
}