英文:
Assignment to a new variable when deleting an element in a slice yields unexpected result
问题
我在尝试删除切片中的一个元素时遇到了一些意外的行为。以下是我的代码:
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)
}
输出结果为:
[1 2 3 5 6 7 8 8]
[1 2 3 5 6 7 8]
我期望的输出是:
[1 2 3 4 5 6 7 8]
[1 2 3 5 6 7 8]
为什么结果不符合我的期望?
换句话说,由于没有对值 x
进行赋值更改,我期望它具有相同的初始值,但由于某种原因它并没有,并且与 y
具有相同的值,最后一个元素重复了。这是一个 bug 吗?
英文:
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?
答案1
得分: 3
append
函数在有足够空间时会原地操作。为了避免这种行为,可以通过切片容量来避免:
y := append(x[:3:3], x[4:]...)
英文:
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:]...)
答案2
得分: 1
这是发生的情况,当你添加时,x会改变。
x = [1,2,3, 4,5,6,7, 8]
[1,2,3] [5,6,7,8] # 第4、5、6、7个元素被改变
x[:3] x[4:]
x = [1,2,3,5,6,7,8,8]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论