Sobes.tech
Junior — Middle

What consequences may arise if you try to add elements to a slice exceeding its current capacity?

sobes.tech AI

Answer from AI

When adding elements to a slice in Go, if its current capacity is exceeded, a new array with increased capacity is allocated, and all existing elements are copied to this new array.

This results in the following consequences:

  • Increased memory usage — a new array is allocated, and the old one remains in memory until garbage collected.
  • Data copying — the copy operation can be costly for large slices.
  • Change of underlying array address — if you have references to the old array, they become outdated.

Example:

s := make([]int, 0, 2) // length 0, capacity 2
s = append(s, 1, 2)    // now length 2
s = append(s, 3)       // capacity exceeded, new array allocated

Therefore, when working with large slices, it is recommended to pre-allocate sufficient capacity if the expected size is known.