我在golang中迭代一个切片并逐个挑选元素。我遇到的问题是,在删除项目后,我应该重置索引或从头开始,但我不确定如何。
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)
}
}
将返回以下内容:
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
这样做的惯用方法是什么? 我马上就是来自Python的i - 或i = i-1。
答案 0 :(得分:1)
我个人更喜欢创建副本。但如果你改变range
部分:
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)
}
}