Junior — Middle
What happens to the original slice after adding an element through append when using its slice?
sobes.tech AI
Answer from AI
In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity. When you take a slice of an original slice and add an element using append, the behavior depends on the current capacity of the slice:
- If the capacity of the slice is sufficient, append will add the element to the same underlying array, and the original slice will also 'see' the changes, as they share the same array.
- If the capacity is insufficient, append will create a new array, copy the data there, and add the element. In this case, the original slice remains unchanged.
Example:
original := []int{1, 2, 3}
slice := original[:2] // [1, 2]
slice = append(slice, 4) // if capacity allows, original will change
fmt.Println(original) // may output [1 2 4]
Thus, append can modify the original slice if the extension occurs within the bounds of the existing array; otherwise, a new array is created, and the original slice remains unchanged.