【发布时间】:2017-08-15 03:53:51
【问题描述】:
我正在遍历 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
这样做的惯用方法是什么? 我立即认为 i-- 或 i = i-1 来自 Python。
【问题讨论】:
-
惯用的做法是不修改您正在迭代的集合,而是迭代地构建一个新集合。
-
play.golang.org/p/6_91N2LWQA 如果必须的话,但你真的不需要像那样重复复制所有切片元素。
-
或者,您是否只想在每次迭代中弹出第一个元素? play.golang.org/p/WgMpEGpZQV
-
感谢您的回复 - 现在更好理解了。