Last active
November 10, 2019 23:53
-
-
Save r6m/3ca00d5603b0ac20ca161354439d2aa0 to your computer and use it in GitHub Desktop.
golang check if item exists in slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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