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

huangapple go评论84阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

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 &quot;:(&quot;} // bad
	for _, fi := range funcs {
		f := reflect.ValueOf(fi)
		functype := f.Type()
		good := false
		for i:=0; i&lt;functype.NumIn(); i++ {
			if &quot;int&quot;==functype.In(i).String() {
				good = true // yes, there is an int among inputs
				break
			}
		}
		for i:=0; i&lt;functype.NumOut(); i++ {
			if &quot;int&quot;==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

huangapple
  • 本文由 发表于 2012年9月17日 23:22:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/12462377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定