reflection - Golang: Function to determine the arity of functions? -
is possible write function determine 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 + + c } fmt.println(arity(add_3_ints)) //prints 3
you can write such function using reflect
package:
import ( "reflect" ) func arity(value interface{}) int { ref := reflect.valueof(value) tpye := ref.type() if tpye.kind() != reflect.func { // define own logic here panic("value not function") } return tpye.numin() }
Comments
Post a Comment