This question already has an answer here:
I would like to check if a value is in a slice of values. What is the best way to achieve this? Something like the following:
if "foo" in []string{"foo", "bar"}...
I've written the following code but not sure how idiomatic it is (golang newbie):
// Convert a slice or array of a specific type to array of interface{}
func ToIntf(s interface{}) []interface{} {
v := reflect.ValueOf(s)
// There is no need to check, we want to panic if it's not slice or array
intf := make([]interface{}, v.Len())
for i := 0; i < v.Len(); i++ {
intf[i] = v.Index(i).Interface()
}
return intf
}
func In(s []interface{}, val interface{}) bool {
for _, v := range s {
if v == val {
return true
}
}
return false
}
So, to use this, here is a test method I wrote.
func TestIn(t *testing.T) {
s := []string{"foo", "bar", "kuku", "kiki"}
for _, v := range s {
if !In(ToIntf(s), v) {
t.Error("Should be in")
}
}
if In(ToIntf(s), "foobar") {
t.Error("Should not be in")
}
}
</div>