【问题标题】:Go: compare two slices and delete multiple indicesGo:比较两个切片并删除多个索引
【发布时间】:2016-07-06 11:35:06
【问题描述】:

如何根据比较遍历两个切片并删除多个索引?我尝试了以下方法,但它导致错误“恐慌:运行时错误:切片超出范围。”

package main

import (
    "fmt"
)

func main() {
    type My struct {
        SomeVal string
    }

    type Other struct {
        OtherVal string
    }

    var MySlice []My
    var OtherSlice []Other

    MySlice = append(MySlice, My{SomeVal: "abc"})
    MySlice = append(MySlice, My{SomeVal: "mno"})
    MySlice = append(MySlice, My{SomeVal: "xyz"})

    OtherSlice = append(OtherSlice, Other{OtherVal: "abc"})
    OtherSlice = append(OtherSlice, Other{OtherVal: "def"})
    OtherSlice = append(OtherSlice, Other{OtherVal: "xyz"})

    for i, a := range MySlice {
        for _, oa := range OtherSlice {
            if a.SomeVal == oa.OtherVal {
                MySlice = MySlice[:i+copy(MySlice[i:], MySlice[i+1:])]
            }
        }
    }

    fmt.Println(MySlice)
}

http://play.golang.org/p/4pgxE3LNmx

注意:如果只找到一个匹配项,则上述方法有效。找到两个匹配项时会发生错误。

【问题讨论】:

标签: loops go compare slice


【解决方案1】:

好的,事情就是这样,一旦从切片中删除索引,剩余的索引就会移动位置,从而取消循环计数。该问题已通过减少循环计数变量得到解决。

for i := 0; i < len(MySlice); i++ {
    for _, oa := range OtherSlice {
        if MySlice[i].SomeVal == oa.OtherVal {
                MySlice = append(MySlice[:i], MySlice[i+1:]...)
                i--
                break
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 2014-07-15
    • 1970-01-01
    • 2015-07-13
    • 2017-03-12
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多