Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

oshosanya commented Nov 21, 2018

What if callDynamically is supposed to return a value?

@roger-king

This comment has been minimized.

Copy link

roger-king commented Feb 23, 2019

What if callDynamically is supposed to return a value?

You just have to assign the callback:

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

@fex

This comment has been minimized.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.