Reputation: 1362
Is it possible to write a function to determine the arity of arbitrary functions, such that:
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
Upvotes: 4
Views: 367
Reputation:
You can write such a function using the reflect
package:
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()
}
Upvotes: 5