Golang:确定功能的泛函?

frm*_*aul 4 reflection go

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

1。

func mult_by_2(x int) int {
      return 2 * x
}
fmt.Println(arity(mult_by_2)) //Prints 1
Run Code Online (Sandbox Code Playgroud)

2。

func add(x int, y int) int {
      return x + y
}
fmt.Println(arity(add)) //Prints 2
Run Code Online (Sandbox Code Playgroud)

3。

func add_3_ints(a, b, c int) int {
      return b + a + c
}
fmt.Println(arity(add_3_ints)) //Prints 3
Run Code Online (Sandbox Code Playgroud)

Tim*_*per 5

您可以使用以下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()
}
Run Code Online (Sandbox Code Playgroud)