0Pricing
Go Academy · Lesson

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()) // 5

Argument 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") }
}

All lessons in this course

  1. reflect.Type and reflect.Value
  2. Inspecting Struct Fields and Tags
  3. Dynamic Function Calls
  4. Practical Reflection: Serializers
← Back to Go Academy