Skip to content

Instantly share code, notes, and snippets.

@Martin91
Last active May 20, 2021 01:54
Show Gist options
  • Save Martin91/08067d7329942459077ed6851ce379fd to your computer and use it in GitHub Desktop.
Save Martin91/08067d7329942459077ed6851ce379fd to your computer and use it in GitHub Desktop.
containsAny in Golang
package main
import (
"fmt"
"reflect"
)
func containsAny(data interface{}, element ...interface{}) bool {
rVal := reflect.ValueOf(data)
switch rVal.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < rVal.Len(); i++ {
ele := rVal.Index(i)
for _, e := range element {
if reflect.DeepEqual(ele.Interface(), e) {
return true
}
}
}
case reflect.String:
str := rVal.Interface().(string)
for _, e := range element {
if subStr, ok := e.(string); ok {
if strings.Contains(str, subStr) {
return true
}
}
}
case reflect.Map:
keys := map[interface{}]bool{}
for _, key := range rVal.MapKeys() {
keys[key.Interface()] = true
}
if len(keys) != 0 {
for _, e := range element {
if keys[e] {
return true
}
}
}
}
return false
}
func main() {
data := []interface{}{1, 2, "a", 'b'}
fmt.Println(containsAny(data, 1, "c"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment