Skip to content

Instantly share code, notes, and snippets.

@timoyuen
Forked from r6m/slice_exists.go
Created May 11, 2018 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timoyuen/5a71cf8b2b3f7c62df832bf9b0e857c0 to your computer and use it in GitHub Desktop.
Save timoyuen/5a71cf8b2b3f7c62df832bf9b0e857c0 to your computer and use it in GitHub Desktop.
golang check if item exists in slice
package main
import(
"fmt"
"reflect"
)
func main() {
items := []int{1,2,3,4,5,6}
fmt.Println(SliceExists(items, 5)) // returns true
fmt.Println(SliceExists(items, 10)) // returns false
}
func SliceExists(slice interface{}, item interface{}) bool {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("SliceExists() given a non-slice type")
}
for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment