Skip to content

Instantly share code, notes, and snippets.

@bowmanmike
Created February 22, 2017 19:06
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bowmanmike/6fe2b840518a59c5cfd0ca5fbaea5751 to your computer and use it in GitHub Desktop.
Save bowmanmike/6fe2b840518a59c5cfd0ca5fbaea5751 to your computer and use it in GitHub Desktop.
Golang Dynamic Function Calling
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)
}
@huahuayu
Copy link

huahuayu commented Apr 2, 2021

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