如果我有任意数量的函数的切片或数组,如何选择只返回int类型的函数或只选择需要int类型参数的函数?
我想我需要使用反射包,但仅仅阅读文档并没有帮助我弄清楚具体该如何做。
如果我有任意数量的函数的切片或数组,如何选择只返回int类型的函数或只选择需要int类型参数的函数?
我想我需要使用反射包,但仅仅阅读文档并没有帮助我弄清楚具体该如何做。
这个程序打印出以整数 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)
}
}
}
我认为这段代码很容易理解。
type Node struct { Neighbors []*Node; Fn func(int...) int}
,或者使用递归接口,如type Node interface { Children []Node; Fn(int...) int }
。可能有一种方法可以避免反射,这将为您节省一些麻烦。Rob Pike 的演讲“Go 中的词法扫描”讨论了递归接口的事情。它非常有用。 - jorellitype Node struct { F interface{} }
并将函数放入其中,你可以使其更易于维护:http://play.golang.org/p/ANJBr1i8Zh。很酷的问题。 - jorelli