Idiomatic way to implement generic functions in Go
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 ?
No comments:
Post a Comment