Slice capacity
Capacity is how many elements the backing array can hold from the start of the slice without allocating a new array. len is how many are in use. append reallocates when len would exceed cap.
Detailed Explanation
A slice header stores len and cap. len is the live window. cap is that window plus unused room to the right on the same array. s[len(s):cap(s)] is the unused tail — you cannot index it with s[i] until you extend len by slicing or appending.
make sets both. make([]int, 3) has len 3 and cap 3. make([]int, 0, 8) has len 0 and cap 8: empty, ready to append eight times without a new array. make([]int, 8) has eight zeros already; appending a ninth grows.
Reslicing changes len, not the array. If cap(s) >= 4, s = s[:4] is legal even when len(s) was 2. You are revealing zeros (or leftover data) that were already in the array. This is how bytes.Buffer reuses memory, and how a forgotten s[:0] can leak old bytes into a later fill.
Growth is geometric. When append needs a new array, it picks a larger capacity (roughly double for small slices, then a smaller factor). Do not depend on the exact multiplier; it has changed across releases. If you know the final size, make([]T, 0, n) or make([]T, n) avoids repeated copies.
Full slice expressions clip cap. s[i:j:k] has length j-i and capacity k-i. The third index must satisfy j <= k <= cap(s). Clipping is how you stop a callee's append from writing into your array past the window you meant to share.
What it costs. Unused capacity is reserved memory. A slice of length 2 and capacity 1e6 holds a million-element array alive. That is the slice-leak pattern: reslice to a small window and keep the header. Copy the small window into a new slice when you store it long-term.
Code Examples
package main
import "fmt"
func main() {
s := make([]int, 0, 4)
fmt.Println(len(s), cap(s)) // 0 4
s = append(s, 1, 2)
fmt.Println(len(s), cap(s)) // 2 4
s = append(s, 3, 4, 5)
fmt.Println(len(s), cap(s)) // 5 >= 8 typically
}func reuse(s []int) []int {
s = s[:0] // len 0, same cap, same array
return append(s, 7)
}func handOff(s []int) []int {
return s[1:3:3] // callee append cannot overwrite s[3]
}Common Gotchas
A small `len` can pin a huge array
copy when you keep a tiny subslice from a large buffer.
`append` does not grow when `len+n <= cap`
it writes into the existing array, which may be shared with another slice.
Capacity is measured from the slice start
`s[2:]` has a smaller cap than `s` even though it is the same array.