I need to create a function that wraps an inner function, and has exactly the same signature as the inner function. I am fearing that this is not possible since Go does not support generics, but perhaps it is achievable using reflect
? The following is the pseudo-go I would like to have:
func myFunc(a int, b string) (string, error) {
return string(a) + b, nil
}
func wrapInner(inner interface{}) interface{} {
argTypes := argsOf(inner)
returnTypes := returnsOf(inner)
wrapper := func(args argTypes) returnTypes {
// do something with inner's args
modArgs := doSomething(args)
ret := inner(modArgs)
// do something with the return
modRet := doSomething(ret)
}
return wrapper
}
wrapped := wrapInner(myFunc)
val, err := wrapped(1, "b")
The pseudo-code is full of errors, but the idea is that wrapInner
has no clue about the signature of inner
. However, it is able to inspect the signature (using, perhaps, reflect
?) and creates a function that adds logic to inner and has exactly the same signature as inner. Is this possible?
interface{}
which means you'd have to call it using reflection. There's no way to return a function with an signature that isn't known at compile time and call it directly. – Adrian