This is a creation in Article, where the information may have evolved or changed.
The Golang ' s function is a code block like C's, but it can also are assigned to a variable as their other types.
If you aren't familiar with the function, Codewalk:first-class Functions in Go should is a good starting point for you. Already known it? Let's go on.
First of all, look at this PHP codes:
function Foobar () { echo "Hello golang\n";} $funcs = Array ( "foobar" = "Foobar", "Hello" = "Foobar"), $funcs ["Foobar"] (); $funcs ["Hello"] ();
It'll print:
mikespook@mikespook-laptop:~/desktop$ php foobar.php Hello golanghello Golang
It is very useful for calling a function with name matching.
So, was it possible to call a function by its name in Golang?
As a static, compiled programming language, the answer is No ... and YES!
You can does this in Golang:
Func Foobar () { //Bla...bla...bla ...} FuncName: = "Foobar" FuncName ()
Can do:
Func Foobar () { //Bla...bla...bla ...} Funcs: = Map[string]func () {"Foobar": foobar}funcs["Foobar"] ()
But here's a limitation that the map is work with the prototype "func ()", no input parameters and return arguments.
If you want to call some functions has different function ' s prototypes, the interface{} should be used.
yep! interface{}, like the void pointer in C. Remember? No? Never mind! Read this:the Go Programming Language specification:interface types.
Then we could add functions with different prototypes into one map:
Func foo () { //Bla...bla...bla ...} Func Bar (A, b, C int) { //Bla...bla...bla ...} Funcs: = map[string]interface{}{"foo": foo, "Bar": Bar}
How does a function in the map? Like this?
funcs["foo"] ()
No! It does not work! You can not call a function stored in a empty interface variable directly.
Dadadada ...
Reflection comes to Us! It's a package called "reflect" in Golang. Do you know reflection already?
If not, just read this:laws of reflection.
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 the 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)
Reflecting the function variable, use reflect. Call to call it and pass parameters into it at the same time.
Nothing could is hard to understand.
I ' ve done a package for this functional:https://bitbucket.org/mikespook/golib/src/27c65cdf8a77/funcmap.
Hope this helps. Have a good time, gophers!