【问题标题】:Iterating through a slice and resetting the index - golang遍历切片并重置索引 - golang
【发布时间】: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
  • 感谢您的回复 - 现在更好理解了。

标签: go slice


【解决方案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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2013-06-25
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多