英文:
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?
答案1
得分: 1
append
操作只是将底层数组的元素向后移动。newSlice
和mySlice
是两个具有相同底层数组的切片。唯一的区别是两者的长度:在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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论