从Golang的函数列表中选择一个函数 [英] Selecting a function from a list of functions in Golang
本文介绍了从Golang的函数列表中选择一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为我需要使用反射包,但只是阅读文档并没有真正帮助我弄清楚如何做到这一点。
该程序打印以 int
作为参数或返回 int
的函数:
包主
pre>
$ b导入(
fmt
反映
$ b $ func main(){
funcs:= make([] interface {},3,3)//我使用interface {}来允许任何类型的func
funcs [0] = func(a int)(int){return a + 1} // good
funcs [1] = func(a string)(int){return len(a)} //好的
funcs [2] = func(一个字符串)(字符串){返回:(} //不好的
用于_,fi:=范围funcs {
f:= reflect.ValueOf (fi)
functype:= f.Type()
good:= false
for i:= 0; I< functype.NumIn(); i ++ {
ifint== functype.In(i).String(){
good = true //是,输入中有一个int
break
}
}
for i:= 0; I< functype.NumOut(); i ++ {
ifint== functype.Out(i).String(){
good = true //是,输出中有一个int
break
}
}
if good {
fmt.Println(f)
}
}
}
我认为代码是自我解释的
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 anint
: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
这篇关于从Golang的函数列表中选择一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文