如何根据比较遍历两个切片并删除多个索引?我尝试了以下操作,但会导致错误“恐慌:运行时错误:切片边界超出范围”。
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
注意:如果仅找到一个匹配项,则上述方法有效。当找到两个匹配项时会发生错误。
达令说
相关分类