Middle
What happens to a slice in Go when it grows and reaches its capacity limit? How does the logic work when adding new elements?
sobes.tech AI
Answer from AI
When a slice in Go reaches its current capacity and a new element is added via append, a memory reallocation occurs:
- A new array with increased capacity is created. Usually, the new capacity is about twice the old one, but the exact algorithm depends on the implementation and the size of the slice.
- The contents of the old array are copied into the new one.
- The new element is added to the new array.
- The slice starts referencing the new array with the updated length and capacity.
This allows slices to grow dynamically, but the append operation can be costly if reallocation occurs.
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 increases, for example, to 4
Thus, append automatically manages the growth of the slice, hiding the details of reallocation from the developer.