是否可以編寫一個函數來確定任意函數的數量,例如: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()
}
- 1 回答
- 0 關注
- 201 瀏覽
添加回答
舉報
0/150
提交
取消
