package main
import (
"log"
"reflect"
)
func main() {
xs := []int{3, 3, 1, 3, 6, 3}
RemoveElem(&xs, func(x interface{}) bool {
if x.(int) == 3 {
return true
}
return false
})
log.Println(xs)
}
func RemoveElem(xs interface{}, removefunc func(x interface{}) bool) {
resultv := reflect.ValueOf(xs)
slicev := resultv.Elem()
for i := slicev.Len() - 1; i >= 0; i-- {
if removefunc(slicev.Index(i).Interface()) {
slicev = reflect.AppendSlice(slicev.Slice(0, i), slicev.Slice(i+1, slicev.Len()))
}
}
resultv.Elem().Set(slicev)
}
func RetainElem(xs interface{}, retainfunc func(x interface{}) bool) {
RemoveElem(xs, func() func(x interface{}) bool {
return func(x interface{}) bool {
return !retainfunc(x)
}
}())
}
网友评论