You cannot get a function by name, and that is what you are trying to do. The reason is that if the Go tool can detect that the function is not explicitly mentioned (and therefore not available), it may not even compile into an executable binary. See the " Client / Server Code Separation " section for details.
With feature registry
One way to do what you want is to create a “function registry” before calling them:
registry := map[string]func(){ "MyFunc1": MyFunc1, "MyFunc2": MyFunc2, "MyFunc3": MyFunc3, } for k := 1; k <= 3; k++ { registry[fmt.Sprintf("MyFunc%d", k)]() }
Conclusion (try on the Go Playground ):
Hello MyFunc1 Hello MyFunc2 Hello MyFunc3
Manual Routing
Similarly to the registry, it checks the name and manually directs the function, for example:
func callByName(name string) { switch name { case "MyFunc1": MyFunc1() case "MyFunc2": MyFunc2() case "MyFunc3": MyFunc3() default: panic("Unknown function name") } }
Use this:
for k := 1; k <= 3; k++ { callByName(fmt.Sprintf("MyFunc%d", k)) }
Try it on the Go Playground .
Note: whether you want callByName() to call the function, callByName() by its name, in the auxiliary function callByName() , or you can choose to return the value of the function (such as func() ) and call it at the place of the call.
Convert functions to methods
Also note that if your functions are actually methods of some kind, you can do this without a registry. Using reflection, you can get a method named: Value.MethodByName() . You can also get / list all methods without knowing their names using Value.NumMethod() and Value.Method() (also see Type.NumMethod() and Type.Method() if you need a method name or types of its parameters )
Here's how to do it:
type MyType int func (m MyType) MyFunc1() { fmt.Println("Hello MyFunc1") } func (m MyType) MyFunc2() { fmt.Println("Hello MyFunc2") } func (m MyType) MyFunc3() { fmt.Println("Hello MyFunc3") } func main() { v := reflect.ValueOf(MyType(0)) for k := 1; k <= 3; k++ { v.MethodByName(fmt.Sprintf("MyFunc%d", k)).Call(nil) } }
The output is the same. Try it on the Go Playground .