Slice capacity
March 7, 2023
Slice types
…
The array underlying a slice may extend past the end of the slice. The capacity is a measure of that extent: it is the sum of the length of the slice and the length of the array beyond the slice; a slice of length up to that capacity can be created by slicing a new one from the original slice. The capacity of a slice a can be discovered using the built-in function
cap(a)
.
Let’s explore this capacity concept a bit by expanding our previous examples:
var a = [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
var s = a[3:6]
fmt.Println(a, s) // Prints: [0 1 2 3 4 5 6 7 8 9] [3 4 5]
fmt.Println(len(s), cap(s)) // Prints: 3 7
So here we see that the length of our slice s
is 3, as expected. The capacity, however, is 7, indicating that the backing array has an additional 4 elements allocated into which the slice can expand, without allocating any additional memory. We can see this in action (and also further demonstrate that slices share storage with their backing array) with the following code:
s = append(s, 99)
fmt.Println(a, s) // Prints: [0 1 2 3 4 5 99 7 8 9] [3 4 5 99]
fmt.Println(len(s), cap(s)) // Prints: 4 7
See it in the playground.
A new, initialized slice value for a given element type
T
may be made using the built-in functionmake
, which takes a slice type and parameters specifying the length and optionally the capacity. A slice created with make always allocates a new, hidden array to which the returned slice value refers. That is, executingmake([]T, length, capacity)
produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:
make([]int, 50, 100) new([100]int)[0:50]
Here we see that the handy make
function gives us the option to pre-allocate additional storage for a slice, in cases where we know we’ll need a slice of a particular size.
This is commonly useful when building a new slice by iterating over another slice or a map. This avoids re-allocating new arrays (and thus unncessarily taxing the garbage collector) every time the backing array’s capacity is exceeded. For example:
var ints = []int{1, 2, 3, 4, 5}
var strs = make([]string, 0, len(integers)) // Set strs to have the same capacity as ints' length
for _, i := range ints {
strs = append(strs, strconv.Itoa(i))
}
Quotes from The Go Programming Language Specification Version of December 15, 2022