Let's say I want to write a function to check whether a predicate is matched for an element in a slice:
func IsIn(array []T, pred func(elt T) bool) bool {
for _, obj := range array {
if pred(obj) { return true;}
}
return false;
}
Obviously, the previous code won't compile, since T
does not exist. I can replace it with some interface{}
like this:
func IsIn(array[]interface{}, pred func(elt interface{}) bool) bool {
...
}
As I am happy to let the predicate perform the casting:
IsIn([]interface{}{1,2,3,4}, func(o interface{}) {return o.(int) == 3; });
But then, the function won't accept any array which is not of type []interface{}
:
IsIn([]int{1,2,3,4}, func(o interface{}) { return o.(int) == 3; }) // DO NOT COMPILE
And similarly:
func IsIn(arr interface, pred func(o interface{}) bool) bool {
for _, o := range arr.([]interface{}) { ... }
}
IsIn([]int{1,2,3,4}, func(o interface{}) { return o.(int) == 3; }) // PANICS AT RUNTIME (cannot cast []int to []interface)
The other alternative is to have typed functions for each array type:
IsInInt(arr []int, pred func(i int) bool) { ... }
IsInStr(arr []string, pred func(s string) bool) { ... }
...
But it seems like a LOT of code duplication.
Has anyone come up with an nice way to deal with such situations ?
EDIT
Thanks to jnml's fantastic tips on Go reflection, I think I have found a nice way to express these patterns, by converting every 'iterable' to a channel:
func iter(obj interface{}) chan interface{} {
c := make(chan interface{})
v := reflect.ValueOf(obj)
if (v.Kind() == reflect.Array || v.Kind() == reflect.Slice) {
go func() {
for i := 0; i < v.Len(); i++ {
c<-v.Index(i).Interface()
}
close(c)
}()
} else if v.Kind() == reflect.Chan {
go func() {
x, ok := v.Recv()
for ok {
c<-x.Interface()
x,ok = v.Recv()
}
close(c)
}()
} else if (... whatever iteration protocol you have ...) {
} else {
panic("Cannot iterate !")
}
return c;
}
With my initial example rewritten using it on the playground.
Thanks a lot to jnml and ANisus for helping out !