Selecting a function from a list of functions in Golang

强颜欢笑 提交于 2019-12-04 03:23:55

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!