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)
}
@oshosanya
Copy link

What if callDynamically is supposed to return a value?

@roger-king
Copy link

What if callDynamically is supposed to return a value?

You just have to assign the callback:

funcMap["hello"].(func() string)()

@fex
Copy link

fex commented Apr 30, 2019

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.

@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