从切片中删除一个元素会在Go语言中复制最后一个元素吗?

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

Removing an element from a slice duplicates the last element in Go?

问题

我正在使用切片在Go语言中进行操作,以更好地理解其行为。我编写了以下代码:

func main() {
	// 初始化
	myslice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	newSlice := myslice

	fmt.Println(myslice)
	fmt.Println(newSlice)

	removeIndex := 3
	newSlice = append(newSlice[:removeIndex], newSlice[removeIndex+1:]...)
	fmt.Println(myslice)
	fmt.Println(newSlice)
}

这是输出结果:

[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]

[1 2 3 5 6 7 8 9 9]
[1 2 3 5 6 7 8 9]

我不太理解为什么newSlice会在末尾重复出现9。另外,这是否意味着这个操作会从底层数组中删除给定的元素?

链接:https://go.dev/play/p/pf7jKw9YcfL

英文:

I was playing with slices in go to better understand the behaviour.
I wrote the following code:

func main() {
	// Initialize
	myslice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	newSlice := myslice

	fmt.Println(myslice)
	fmt.Println(newSlice)

	removeIndex := 3
	newSlice = append(newSlice[:removeIndex], newSlice[removeIndex+1:]...)
	fmt.Println(myslice)
	fmt.Println(newSlice)


}

This is the output:

[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]

[1 2 3 5 6 7 8 9 9]
[1 2 3 5 6 7 8 9]

I dont really understand what happens with newSlice that duplicates the 9 at the end. Also, does this mean, that this operation removes the given element from the underlying array?

https://go.dev/play/p/pf7jKw9YcfL

答案1

得分: 1

append操作只是将底层数组的元素向后移动。newSlicemySlice是两个具有相同底层数组的切片。唯一的区别是两者的长度:在append操作之后,newSlice有8个元素,而mySlice仍然有9个元素。

英文:

The append operation simply shifts the elements of the underlying array. newSlice and mySlice are two slices with the same underlying array. The only difference is the length of the two: After append, newSlice has 8 elements, and mySlice still has 9 elements.

huangapple
  • 本文由 发表于 2022年3月7日 23:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/71383811.html
匿名

发表评论

匿名网友

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

确定