Sobes.tech
Middle

How does the capacity of a slice grow when expanded?

sobes.tech AI

Answer from AI

In Go, a slice has an internal capacity that grows when expanded. When an element is added and the current capacity is insufficient, the slice allocates a new array with increased capacity, usually about twice the current one, to minimize the number of allocations.

For example, if a slice has capacity=4, adding a fifth element creates a new array with capacity=8, and the data is copied there. This amortized increase allows efficient management of memory and performance.

Example:

s := make([]int, 0, 4)
for i := 0; i < 10; i++ {
    s = append(s, i)
    fmt.Printf("len=%d cap=%d\n", len(s), cap(s))
}

The output will show how the capacity roughly doubles when needed.