Why does the capacity of the slice change when appending just one more element?

Viewed 24

I am trying the Tour of Go in the playground and I was puzzled as to why the capacity of the slice increased by 2 when I appended a value to the slice for the third time.


import "fmt"

func main() {
    var s []int
    printSlice(s)
    p := &s
    fmt.Println(p)
    // append works on nil slices.
    s = append(s, 0)
    printSlice(s)

    // The slice grows as needed.
    s = append(s, 1)
    printSlice(s)
    
    s = append(s, 2)
    printSlice(s)
    fmt.Println(p)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
} ```
0 Answers
Related