Slice Capacity
Capacity: how much room a slice has
The slices lesson said a slice holds a pointer to a backing array, a length, and a capacity. You've been using the length — here's the third number:
len(s)— how many elements the slice holds right now.cap(s)— how many it could hold before Go has to swap in a bigger backing array.
s := make([]int, 3)
fmt.Println(len(s), cap(s)) // 3 3Go grows the capacity for you
When you append and the backing array is already full, Go quietly allocates a bigger one, copies the existing elements across, and adds the new element there — you never do this by hand:
var s []int
for i := 0; i < 6; i++ {
s = append(s, i)
fmt.Println(len(s), cap(s))
}
// 1 4
// 2 4
// 3 4
// 4 4
// 5 8
// 6 8The capacity jumps in chunks — roughly doubling each time — so these reallocations get rarer as the slice grows and append stays cheap on average. The exact numbers vary by Go version; don't write code that depends on them.
Ask for the size up front when you know it
If you already know how many elements you're about to add, the three-argument make lets you set the capacity now:
nums := make([]int, 0, 100) // len 0, cap 100Appending 100 times to nums allocates nothing extra — the backing array is already big enough.