Basically if I have a slice or array of any arbitrary functions, how can I select only the ones that return int, or select only the ones that take ints?
I figured that I would need to use the reflect package, but just reading the docs didn't really help me figure out exactly how to do it.
This program prints the functions taking an int
as parameter or returning an int
:
package main
import (
"fmt"
"reflect"
)
func main() {
funcs := make([]interface{}, 3, 3) // I use interface{} to allow any kind of func
funcs[0] = func (a int) (int) { return a+1} // good
funcs[1] = func (a string) (int) { return len(a)} // good
funcs[2] = func (a string) (string) { return ":("} // bad
for _, fi := range funcs {
f := reflect.ValueOf(fi)
functype := f.Type()
good := false
for i:=0; i<functype.NumIn(); i++ {
if "int"==functype.In(i).String() {
good = true // yes, there is an int among inputs
break
}
}
for i:=0; i<functype.NumOut(); i++ {
if "int"==functype.Out(i).String() {
good = true // yes, there is an int among outputs
break
}
}
if good {
fmt.Println(f)
}
}
}
I think the code is self explanatory
来源:https://stackoverflow.com/questions/12462377/selecting-a-function-from-a-list-of-functions-in-golang