在切片中删除元素时,将其赋值给一个新变量会产生意外的结果。

huangapple go评论79阅读模式
英文:

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)
}

playground

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]

huangapple
  • 本文由 发表于 2015年3月19日 03:57:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/29131529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定