Q: In golang, how capacity of slice grows when appending elements to it?

A: Golang always give more capacity than you request. Because this improves performance by reducing the number of allocations that are required.

var s []int // nil len: 0, cap: 0
s = append(s, 0) // [0] len: 1, cap: 2 <- not 1
s = append(s, 1, 2, 3, 4) // [0, 1, 2, 3, 4] len: 4, cap: 8 <- not 5

Appending one element to nil slice increases capacity by two

独立页面