go - Examining the signature of function assigned to an interface{} variable using reflection -
i'm trying build generic currying function that's like:
package curry import ( "fmt" "reflect" ) // function type fn interface{} // function parameter type pr interface{} // return curried function func it(f fn, p ...pr) (fn, error) { // examine concret type of function f if reflect.valueof(f).kind() == reflect.func { // slice of input , output parameters type } else { return nil, fmt.errorf("%s", "takes function first parameter") } // _, _ = f, p return nil, nil } is possible extract slice of input , output parameters types []reflect.type of function f ?
you can use reflect.type.in(int) , reflect.type.out(int), there corresponding methods called numin() int , numout() int give number of inputs/outputs.
however, keep in mind few caveats:
- to correctly extract function arbitrary signature, you'll need infinite number of cases. you'll have switch on every single in , out in turn correctly type extract.
- you can't dynamically create function anyway. there's no funcof method go sliceof, mapof, etc. you'll have hand code curried versions anyway.
- using reflection emulate generics considered bad idea™.
if absolutely have this, i'd heavily recommend making interface , having each implementation currying itself, rather trying hack "generically" cases, never work of go 1.2.1.
Comments
Post a Comment