Skip to content

Instantly share code, notes, and snippets.

@huobazi
Created March 23, 2015 00:38
Show Gist options
  • Save huobazi/f69433d35d8cfbc3b7c9 to your computer and use it in GitHub Desktop.
Save huobazi/f69433d35d8cfbc3b7c9 to your computer and use it in GitHub Desktop.
check if a object is ina array
func Contains(obj interface{}, target interface{}) (bool, error) {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true, nil
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true, nil
}
}
return false, errors.New("not in")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment