You can run the example code on Go Playground.
Here is the code:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
_ = append(numbers[0:1], numbers[2:]...)
fmt.Println(numbers)
}
Output:
[1 2 3 4 5]
[1 3 4 5 5]
Why was the numbers
slice modified by append? Is this expected behavior and if yes, could you explain to me why? I thought append
doesn't modify its arguments.
See http://blog.golang.org/go-slices-usage-and-internals.
The append function could allocate a new underlying array if what you are appending to the slice does not fit in the current slice's capacity. Append does modify the underlying array. The reason you have to assign back to the variable is because, as I said in the first sentence, the underlying array could be reallocated and the old slice will still point to the old array.
See this play example to see exactly what I am talking about.