Sobes.tech
Junior — Middle

What happens if you perform an append operation on a slice that has run out of allocated memory?

sobes.tech AI

Answer from AI

If a slice in Go reaches its allocated capacity when calling the append function, a new array with increased capacity is allocated. The contents of the old array are copied into the new one, and then the new element is added. As a result, a new slice pointing to the new array is returned. The old array remains in memory if there are still references to it.

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 is exhausted, a new array with larger capacity is allocated
fmt.Println(s)         // [1 2 3]

Thus, append automatically expands the slice's capacity when needed, allowing dynamic addition of elements without errors.