Sobes.tech
Senior

What is capacity in slices and how is it used?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains a pointer to an array, a length (len), and a capacity (cap). Capacity is the maximum number of elements that the slice can hold without allocating new memory.

When a slice is created, its length is the number of elements it contains, and its capacity is the size of the underlying array starting from the first element of the slice.

If, when adding elements with append, the slice's length exceeds its capacity, a new array with increased capacity is allocated, and the data is copied into it.

Example:

s := make([]int, 2, 5) // length 2, capacity 5
fmt.Println(len(s)) // 2
fmt.Println(cap(s)) // 5

s = append(s, 1, 2, 3) // now length 5, capacity 5

s = append(s, 4) // length 6, capacity increased (e.g., 10)

Capacity helps manage memory efficiently by reducing the number of allocations as the slice grows.

What is capacity in slices and how is it used? — Golang - sobes.tech