Last active
January 13, 2016 04:56
-
-
Save gwang/38b84df927471cd8cd73 to your computer and use it in GitHub Desktop.
Golang: call functions by name using reflection
This file contains 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
// 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