【发布时间】: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
注意:如果只找到一个匹配项,则上述方法有效。找到两个匹配项时会发生错误。
【问题讨论】:
-
旁注,如果只找到一个匹配项,上述方法有效。找到两个匹配项时会发生错误。
-
是的,我认为你是对的。 “删除切片中的元素”解决了同样的问题。