Skip to content

Instantly share code, notes, and snippets.

@eihigh
Created April 12, 2019 09:35
Show Gist options
  • Save eihigh/4aaa1a9ef62c123ea89f58f051f12aee to your computer and use it in GitHub Desktop.
Save eihigh/4aaa1a9ef62c123ea89f58f051f12aee to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
func clean(slice interface{}, isDead func(int) bool) int {
rv := reflect.ValueOf(slice)
swap := reflect.Swapper(slice)
length := rv.Len()
n := 0
for i := 0; i < length; i++ {
if !isDead(i) {
swap(n, i)
n++
}
}
return n
}
func main() {
slice := []int{
1, 1, 0, 1, 1, 0, 0,
}
n := clean(slice, func(i int) bool { return slice[i] == 0 })
slice = slice[:n]
fmt.Println(slice)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment