英文:
Iterating through a slice and resetting the index - golang
问题
我正在遍历一个切片,并逐个选择元素。我遇到的问题是,在删除一个元素后,我应该重置索引或从头开始,但我不确定如何做。
以下是代码的翻译结果:
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 7, 16, 22, 17, 42}
fmt.Println("我们将从以下切片开始:", x)
for i, v := range x {
fmt.Println("当前值为:", v)
x = append(x[:i], x[i+1:]...)
fmt.Println("删除后的切片为:", x)
}
}
输出结果如下:
我们将从以下切片开始: [1 2 3 7 16 22 17 42]
当前值为: 1
删除后的切片为: [2 3 7 16 22 17 42]
当前值为: 3
删除后的切片为: [2 7 16 22 17 42]
当前值为: 16
删除后的切片为: [2 7 22 17 42]
当前值为: 17
删除后的切片为: [2 7 22 42]
当前值为: 42
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox337422483/main.go:13 +0x460
你想知道如何以惯用方式解决这个问题。我立即想到的是从Python中使用i--
或i = i-1
。
英文:
I am iterating through a slice in golang and picking off elements one by one. The problem I am having is that after I remove an item I should either reset the index or start from the beginning but I'm not sure how.
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 7, 16, 22, 17, 42}
fmt.Println("We will start out with", x)
for i, v := range x {
fmt.Println("The current value is", v)
x = append(x[:i], x[i+1:]...)
fmt.Println("And after it is removed, we get", x)
}
}
Will Return the following:
We will start out with [1 2 3 7 16 22 17 42]
The current value is 1
And after it is removed, we get [2 3 7 16 22 17 42]
The current value is 3
And after it is removed, we get [2 7 16 22 17 42]
The current value is 16
And after it is removed, we get [2 7 22 17 42]
The current value is 17
And after it is removed, we get [2 7 22 42]
The current value is 42
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox337422483/main.go:13 +0x460
What is the idiomatic way to do this?
I immediately thing i-- or i = i-1 coming from Python.
答案1
得分: 1
我个人更喜欢创建一个副本。但是如果你改变range
部分,也可以不创建副本来完成:
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 7, 16, 22, 17, 42}
fmt.Println("我们将从", x, "开始")
for i := 0; i < len(x); {
fmt.Println("当前值为", x[i])
x = append(x[:i], x[i+1:]...)
fmt.Println("移除后,我们得到", x)
}
}
英文:
I personally prefer to create a copy. But also it can be done without if you change range
part:
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 7, 16, 22, 17, 42}
fmt.Println("We will start out with", x)
for i := 0; i < len(x); {
fmt.Println("The current value is", x[i])
x = append(x[:i], x[i+1:]...)
fmt.Println("And after it is removed, we get", x)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论