Function call by name in Golang

Source: Internet
Author: User
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.