Skip to content

Instantly share code, notes, and snippets.

@gwang
Last active January 13, 2016 04:56
Show Gist options
  • Save gwang/38b84df927471cd8cd73 to your computer and use it in GitHub Desktop.
Save gwang/38b84df927471cd8cd73 to your computer and use it in GitHub Desktop.
Golang: call functions by name using reflection
// refer to: http://mikespook.com/2012/07/function-call-by-name-in-golang/
func foo() {
// does something
}
func bar(int i1, int i2, int i3) {
// does something else.
}
func Call(m map[string]interface{}, name string, params ... interface{}) (result []reflect.Value, err error) {
f = reflect.ValueOf(m[name])
if len(params) != f.Type().NumIn() {
err = errors.New("The number of params is not adapted.")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
return
}
Call(funcs, "foo")
Call(funcs, "bar", 1, 2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment