Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: pointer to function from string (function's name)

Tags:

Is there any chance to get pointer to function from function's name, presented as string? This is needed for example to send some function as argument to another function. Some sort of metaprogramming, you know.

like image 393
Sergey Gerasimov Avatar asked Aug 02 '13 13:08

Sergey Gerasimov


1 Answers

Go functions are first class values. You don't need to revert to the tricks from dynamic languages.

package main  import "fmt"  func someFunction1(a, b int) int {         return a + b }  func someFunction2(a, b int) int {         return a - b }  func someOtherFunction(a, b int, f func(int, int) int) int {         return f(a, b) }  func main() {         fmt.Println(someOtherFunction(111, 12, someFunction1))         fmt.Println(someOtherFunction(111, 12, someFunction2)) } 

Playground


Output:

123 99 

If the selection of the function depends on some run-time-only known value, you can use a map:

m := map[string]func(int, int) int {         "someFunction1": someFunction1,         "someFunction2": someFunction2, }  ...  z := someOtherFunction(x, y, m[key]) 
like image 74
zzzz Avatar answered Sep 21 '22 18:09

zzzz