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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With