Junior — Middle
How does the size of a slice change when its capacity limits are exceeded in the Go programming language?
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). When adding elements via append, if the slice's length exceeds its current capacity, a new array with increased capacity is allocated, old data is copied, and the slice's pointer is updated.
The size of the new array usually increases by about 2 times the current capacity, but the exact strategy depends on the implementation and the size of the slice. This allows efficient scaling of the slice without frequent allocations.
Example:
s := make([]int, 0, 2) // len=0, cap=2
s = append(s, 1, 2) // len=2, cap=2
s = append(s, 3) // len=3, cap will increase, for example, to 4
Thus, when capacity is exceeded, the slice automatically expands, increasing the internal array to accommodate new elements.