I am new to golang. Tour of Go has this snippet:
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
s = s[:0]
printSlice(s)
s = s[:4]
printSlice(s)
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
and the result:
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
My confusion is cap=4in the last line - I thought it should stay 6. What is the reason for changing the capacity from 6 to 4 in the last line? In addition, why only the last line changes its capacity, while others do not?
source
share