Length and capacity
…
The capacity of a slice is the number of elements for which there is space allocated in the underlying array. At any time the following relationship holds:
0 <= len(s) <= cap(s)
Recall that a slice is backed by a fixed-length array, which may have more elements than the slice. When this is the case, the capacity of the slice is said to be the current length of the slice, plus any unused elements in the backing array that extend beyond the final element of the slice.
That might seem like a lot of unnecessary complication. Why can’t we just say that the capacity of the slice is the length of the array?
a := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(a, len(a), cap(a)) // [0 1 2 3 4 5 6 7 8 9] 10 10
s1 := a[:2]
fmt.Println(s1, len(s1), cap(s1)) [0 1] 2 10
Because the slice may not begin at the beginning of the array! Let me demonstrate:
s2 := a[5:7]
fmt.Println(s2, len(s2), cap(s2)) [5 6] 2 5
The length of a
nil
slice, map or channel is 0. The capacity of anil
slice or channel is 0.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)