Suppose I have a function which resides in the fn
property of the following Method
struct:
type Method struct {
fn interface{}
}
var inst = &Method{func(a, b int) int {
return a + b
}}
Now, I want to invoke this function with two arguments without explicitly casting it to func(int, int) int
like so
a := 5
b := 6
fmt.Println(inst.fn(a, b))
How can I achieve this? Is there some generic solution for this?
The only way I know is by using reflect.Value.Call
:
type Method struct {
fn interface{}
}
func (m Method) Call(args ...interface{}) {
vs := make([]reflect.Value, len(args))
for i := range args {
vs[i] = reflect.ValueOf(args[i])
}
v := reflect.ValueOf(m.fn)
v.Call(vs)
}
func main() {
f := func(a, b int) {
fmt.Println(a + b)
}
m := Method{f}
m.Call(2, 3)
}
Playground: http://play.golang.org/p/JNtj2EMpu7.
Note: this will panic if fn is not a function or if the number or types of arguments are wrong. If you don't want that, you need to recheck all those conditions yourself.