从Golang中的函数列表中选择一个函数

时间:2012-09-17 15:22:55

标签: go reflection go-reflect

基本上,如果我有任意函数的切片或数组,我如何只选择返回int的函数,或者只选择那些采用int的函数?

我认为我需要使用反射包,但只是阅读文档并没有真正帮助我弄清楚如何做到这一点。

1 个答案:

答案 0 :(得分:11)

此程序打印以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)
        }
    }
}

我认为代码是自我解释的

相关问题