Golang:确定函数arity的函数?

时间:2016-02-06 14:55:34

标签: reflection go

是否可以编写一个函数来确定任意函数的arity,例如:

1

Icon ico = Icon.FromHandle((new Icon(Resources.InfoIcon, 256, 256).ToBitmap()).GetHicon());

2

func mult_by_2(x int) int {
      return 2 * x
}
fmt.Println(arity(mult_by_2)) //Prints 1

3

func add(x int, y int) int {
      return x + y
}
fmt.Println(arity(add)) //Prints 2

1 个答案:

答案 0 :(得分:4)

您可以使用reflect包编写此类函数:

import (
    "reflect"
)

func arity(value interface{}) int {
    ref := reflect.ValueOf(value)
    tpye := ref.Type()
    if tpye.Kind() != reflect.Func {
        // You could define your own logic here
        panic("value is not a function")
    }
    return tpye.NumIn()
}