从Golang的函数列表中选择一个函数 [英] Selecting a function from a list of functions in Golang

查看:507
本文介绍了从Golang的函数列表中选择一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

解决方案

该程序打印以 int 作为参数或返回 int 的函数:

 包主
$ 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)
}
}
}
pre>

我认为代码是自我解释的


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 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

这篇关于从Golang的函数列表中选择一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆