Junior — Middle
What happens when calling the append method and why does it return a new slice?
sobes.tech AI
Answer from AI
In Go, the append method is used to add elements to a slice. When calling append, the following happens:
- If the slice has enough capacity, the new element is simply added to the existing array, and a slice pointing to the updated part of the array is returned.
- If the capacity is insufficient, a new array with increased capacity is created, the old elements are copied into it, and then the new element is added.
Therefore, append returns a new slice because:
- In case of capacity expansion, it returns a slice pointing to a new array.
- When capacity is sufficient, it returns a slice pointing to the same array but with an increased length.
It is important to always assign the result of append back to a variable to avoid losing the reference to the updated slice:
s := []int{1, 2, 3}
s = append(s, 4) // s now points to a slice with elements [1 2 3 4]
Thus, append returns a new slice because the underlying array may change internally, and the reference needs to be updated.