Last active
May 20, 2021 01:54
-
-
Save Martin91/08067d7329942459077ed6851ce379fd to your computer and use it in GitHub Desktop.
containsAny in Golang
This file contains 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 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