英文:
Selecting a function from a list of functions in Golang
问题
基本上,如果我有一个任意函数的切片或数组,我该如何选择只返回int的函数,或者选择只接受int参数的函数?
我想我需要使用reflect包,但仅仅阅读文档并没有真正帮助我弄清楚如何做到这一点。
英文:
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.
答案1
得分: 12
这个程序打印了以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)
		}
	}
}
我认为代码本身已经很清楚了。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论