I'm new to golang. A Tour of Go has this snippet:
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v
", 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 the cap=4
in the last line - I thought it should remain 6. What is the cause of the capacity changing from 6 to 4 in the last line? Also, why only the last line changes its capacity but the others don't ?