Dynamic Function Calls
Calling functions and setting values via reflect
Dynamic Function Calls is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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") }
}Variadic functions
Call a variadic function with Value.Call (spreading the slice) or Value.CallSlice (passing the variadic args as a slice value):
sum := reflect.ValueOf(func(ns ...int) int {
total := 0
for _, n := range ns { total += n }
return total
})
args := reflect.ValueOf([]int{1,2,3})
results := sum.CallSlice([]reflect.Value{args})reflect.MakeFunc
reflect.MakeFunc creates a new function at runtime with a given type and a wrapper body. Used to generate adapter functions for interfaces.
t := reflect.TypeOf(func(int) string { return "" })
fn := reflect.MakeFunc(t, func(args []reflect.Value) []reflect.Value {
return []reflect.Value{reflect.ValueOf(strconv.Itoa(args[0].Interface().(int)))}
})Calling methods by name
Retrieve a method by name and call it:
v := reflect.ValueOf(myObj)
m := v.MethodByName("Process")
if m.IsValid() {
m.Call(nil)
}Checking if method exists
Always check m.IsValid() before calling — MethodByName returns the zero Value if the method is not found, and calling the zero Value panics.
Dynamic dispatch use cases
Dynamic function calls are used in: plugin systems (call functions by string name), test frameworks (call TestXxx functions), RPC dispatchers (map method names to handlers), and decorators.
Performance
reflect.Call is ~10-50× slower than a direct call. Cache the reflect.Value of frequently called functions; avoid in hot loops.
Type-safe wrapper
Wrap dynamic calls in a typed helper that performs the reflect machinery once during startup and calls the cached Value repeatedly:
type Processor func(context.Context, []byte) ([]byte, error)
// Build at startup, reuse at request timeError return handling
If the function returns an error as its last result, extract and check it:
results := fn.Call(args)
if !results[len(results)-1].IsNil() {
return results[len(results)-1].Interface().(error)
}Alternatives to reflection
If the set of functions is known at compile time, use a map of function values (map[string]func(...)) instead of reflection — it is safer and faster.
handlers := map[string]func(ctx context.Context, req []byte) []byte{
"greet": greetHandler,
}Quick Check
What does reflect.Value.Call return?
Recap: Dynamic Function Calls
Key points:
- Value.Call([]reflect.Value) invokes the function; returns []reflect.Value
- Check m.IsValid() before calling MethodByName result
- MakeFunc creates a new function with a given type at runtime
- Prefer map[string]func over reflection for known function sets
Frequently asked questions
Is the “Dynamic Function Calls” lesson free?
Yes — the full text of “Dynamic Function Calls” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Dynamic Function Calls”?
Calling functions and setting values via reflect You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Dynamic Function Calls” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.