CodeBlanks Logo Icon CodeBlanks

Dynamic call

Learn to dynamically call functions and methods with reflect.

Calling a method by name

MethodByName("Name") finds a value's method by a name given as text; Call runs it. Arguments and return values travel as []reflect.Value.

m := reflect.ValueOf(h).MethodByName("Topla")
out := m.Call([]reflect.Value{reflect.ValueOf(2), reflect.ValueOf(3)})
fmt.Println(out[0].Int())  // 5

Plugin systems that map command names to methods work this way.

Only exported methods

Reflect only sees methods whose names start with an upper-case letter. Also, if the method has a pointer receiver (func (h *Hesap)), you must pass reflect.ValueOf(&h).

fmt.Println(reflect.TypeOf(&h).NumMethod())  // number of exported methods

Practice Call it by name

Define type Hesap struct{} and func (Hesap) Kare(n int) int { return n * n }. Find the method with MethodByName("Kare"), Call it with argument 4 and print the result's Int().

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

type Hesap struct{}

func (Hesap) Kare(n int) int { return n * n }

func main() {
    m := reflect.ValueOf(Hesap{}).MethodByName("Kare")
    out := m.Call([]reflect.Value{reflect.ValueOf(4)})
    fmt.Println(out[0].Int())
}

Expected output

16

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>MethodByName</code> return if the method doesn't exist?

  • An empty slice
  • An invalid Value (IsValid() is false) Correct answer
  • A nil error
  • A compile error

Explanation: A zero Value is returned for a missing method; calling Call without checking IsValid() panics.

2 Run the method

Question
m := reflect.ValueOf(s).MethodByName("Selam")
m.____(nil)
Answer
m := reflect.ValueOf(s).MethodByName("Selam")
m.Call(nil)

Explanation: Call runs the method with the given argument slice; nil can be passed when there are no arguments.

3 Dynamic call parts

Term Meaning
MethodByName Finds the method by name
Call Runs the method
[]reflect.Value Argument and result list
IsValid() Was it found?

All lessons in Advanced