Go:比较两个切片并删除多个索引

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


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


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


猛跑小猪
浏览 126回答 1
1回答

达令说

好的,就是这样,一旦从切片中删除索引,剩余的索引就会移动位置,从而使循环计数关闭。该问题已通过递减循环计数变量解决。for i := 0; i < len(MySlice); i++ {&nbsp; &nbsp; for _, oa := range OtherSlice {&nbsp; &nbsp; &nbsp; &nbsp; if MySlice[i].SomeVal == oa.OtherVal {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MySlice = append(MySlice[:i], MySlice[i+1:]...)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i--&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go