为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
牧羊人nacy 2021-12-07 18:54:31
是否可以编写一个函数来确定任意函数的数量,例如:1.func mult_by_2(x int) int {      return 2 * x}fmt.Println(arity(mult_by_2)) //Prints 12.func add(x int, y int) int {      return x + y}fmt.Println(arity(add)) //Prints 23.func add_3_ints(a, b, c int) int {      return b + a + c}fmt.Println(arity(add_3_ints)) //Prints 3
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

您可以使用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()

}


查看完整回答
反对 回复 2021-12-07
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信