Golang:函数确定函数的数量?

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


1.


func mult_by_2(x int) int {

      return 2 * x

}

fmt.Println(arity(mult_by_2)) //Prints 1

2.


func add(x int, y int) int {

      return x + y

}

fmt.Println(arity(add)) //Prints 2

3.


func add_3_ints(a, b, c int) int {

      return b + a + c

}

fmt.Println(arity(add_3_ints)) //Prints 3


牧羊人nacy
浏览 158回答 1
1回答

HUX布斯

您可以使用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()}
打开App,查看更多内容
随时随地看视频慕课网APP