Dynamic Function Calls
Calling functions and setting values via reflect
reflect.Value.Call
Value.Call(args) calls the function represented by the Value with the given arguments (as a []reflect.Value) and returns the results as a []reflect.Value.
fn := reflect.ValueOf(add)
results := fn.Call([]reflect.Value{
reflect.ValueOf(2),
reflect.ValueOf(3),
})
fmt.Println(results[0].Int()) // 5Argument type checking
Ensure argument types match the function signature before calling. Mismatched types cause a panic.
t := reflect.TypeOf(fn)
if t.NumIn() != len(args) { panic("wrong arg count") }
for i, arg := range args {
if !reflect.TypeOf(arg).AssignableTo(t.In(i)) { panic("type mismatch") }
}