I have a question about the code below
package main
import "fmt"
func main() {
var a []int
printSlice("a", a)
a = append(a, 0)
printSlice("a", a)
a = append(a, 1)
printSlice("a", a)
a = append(a, 2, 3, 4)
printSlice("a", a)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
I always guess what the result of the execution of the code part will look like, and then run the code and check if my assumption is correct. But this code was slightly different from my guess:
Result:
On my local tour server:
a len=0 cap=0 []
a len=1 cap=1 [0]
a len=2 cap=2 [0 1]
a len=5 cap=6 [0 1 2 3 4]
Everything is ok until the last line, but I do not get
cap=6
why not
cap=5
My opinion: I did not create a slice with an explicit capacity, so my system gave it this value of 6 .
2 ). But when I tried the same code on the golang tour server, I get a slightly more varied result:
a len=0 cap=0 []
a len=1 cap=2 [0]
a len=2 cap=2 [0 1]
a len=5 cap=8 [0 1 2 3 4]
What about cap = 2 in the second line and cap = 8 in the last line?