Slice: Length and Capacity

About slice length and capacity

Both arrays and slices support the len() function for finding out their length. However, slices also have an additional property called capacity that can be found using the cap() function.

Note: The capacity of a slice is really important when we want to select a part of a slice or when we want to reference an array using a slice.

Slice capacity

The capacity shows how much a slice can be expanded without the need to allocate more memory and change the underlying array. Although the capacity of a slice is handled by Go after slice creation, a developer can define the capacity of a slice at creation time using the make() function—after that, the capacity of the slice doubles each time the length of the slice is about to become bigger than its current capacity. The first argument of make() is the type of the slice and its dimensions, the second is its initial length, and the third, which is optional, is the capacity of the slice. Although the data type of a slice can’t change after creation, the other two properties can change.

Note: Writing something like make([]int, 3, 2) generates an error message because, at any given time, the capacity of a slice (2) can’t be smaller than its length (3).

Appending a slice or an array

But what happens when we want to append a slice or an array to an existing slice? Should we do that element by element? Go supports the ... operator, which is used for dividing a slice or an array into multiple arguments before appending it to an existing slice.

The figure that follows illustrates with a graphical representation how length and capacity work in slices.

Get hands-on with 1200+ tech skills courses.