How do you loop over two slices and delete multiple indices, based on the comparison? I tried the following, but it results in an error "panic: runtime error: slice bounds out of range."
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
Note: the above works if only one match is found. The error happens when two matches are found.
Okay, so that was the thing, once an index is remove from the slice the remaining indices shift position, throwing the loop count off. The issue was resolved by decrementing the loop count variable.
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
}
}
}