Junior — Middle
How does the size of a slice increase in the Go language?
sobes.tech AI
Answer from AI
In Go language, a slice is a structure that contains a pointer to an array, a length, and a capacity. When adding elements using the append function, if the slice's length reaches its capacity, the capacity is increased.
The mechanism of increasing the slice size is not fixed, but usually Go doubles the capacity to minimize the number of allocations and copies. A new array with increased capacity is created, old data is copied into it, and the slice pointer is updated.
Example:
s := make([]int, 0, 2) // length 0, capacity 2
s = append(s, 1, 2) // now length 2, capacity 2
s = append(s, 3) // capacity will increase, for example, to 4
Thus, the size of the slice increases automatically when elements are added and the current capacity is exhausted.