Created
February 22, 2017 19:06
-
-
Save bowmanmike/6fe2b840518a59c5cfd0ca5fbaea5751 to your computer and use it in GitHub Desktop.
Golang Dynamic Function Calling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
// Use map[string]interface{} to pair functions to name | |
// Could maybe use anonymous functions instead. Might be clean | |
// in certain cases | |
var funcMap = map[string]interface{}{ | |
"hello": hello, | |
"name": name, | |
} | |
func main() { | |
callDynamically("hello") | |
callDynamically("name", "Joe") | |
} | |
func callDynamically(name string, args ...interface{}) { | |
switch name { | |
case "hello": | |
funcMap["hello"].(func())() | |
case "name": | |
funcMap["name"].(func(string))(args[0].(string)) | |
} | |
} | |
func hello() { | |
fmt.Println("hello") | |
} | |
func name(name string) { | |
fmt.Println(name) | |
} |
What if callDynamically is supposed to return a value?
You just have to assign the callback:
funcMap["hello"].(func() string)()
case "hello":
funcMap["hello"].(func())()
This code uses makes two redundant decisions.
You can eigther
get rid of the funcMap, since you already make the decision which function to call in the switch statement
or
get rid of the switch statement (which does not work, since your functions take different parameters, so you need to make the decision in the switch)
More generic would be to only use the functMap approach, but that would force you to use a common function signature.
not dynamic enough
please take a look https://github.com/huahuayu/go-dynamic-call
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if callDynamically is supposed to return a value?