I am seeing some unintended behaviour when trying to delete an element within a slice. Below is my code:
package main
import "fmt"
func main() {
x := []int{1,2,3,4,5,6,7,8}
y := append(x[:3],x[4:]...)
fmt.Println(x)
fmt.Println(y)
}
the output is:
[1 2 3 5 6 7 8 8]
[1 2 3 5 6 7 8]
I would expect the output to be:
[1 2 3 4 5 6 7 8]
[1 2 3 5 6 7 8]
Why is the result not what I expected?
In other words since there is no assignment to change the value x
I would expect it to have the same initialized value but for some reason it doesn't and has the same value as y
with the last element duplicated. Is this a bug?
The append
function operates in-place when enough space is available. Slice away the capacity to avoid this behaviour:
y := append(x[:3:3],x[4:]...)
This is what happens, when you append, x is changed.
x = [1,2,3, 4,5,6,7, 8]
[1,2,3] [5,6,7,8] # 4th, 5th, 6th, 7th elements are changed
x[:3] x[4:]
x = [1,2,3,5,6,7,8,8]