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 hidden or 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not dynamic enough
please take a look https://github.com/huahuayu/go-dynamic-call