首页 > Go语言中怎么通过一个字符串调用对应名称的函数

Go语言中怎么通过一个字符串调用对应名称的函数

先看一个示例代码:

package main

import (
    "fmt"
)

func main() {
    funcs := [3]string{"test1", "test2", "test3"}
    var result string
    for _, v := range funcs {
        switch v {
        case "test1":
            result = test1()
        case "test2":
            result = test2()
        case "test3":
            result = test3()
        default:
            result = "NON"
        }
        fmt.Println(result)
    }
}

func test1() string {
    return "test1"
}

func test2() string {
    return "test2"
}

func test3() string {
    return "test3"
}

上面的代码中函数名通过一个数组传递,有多少个就要写多少个switch/case很是蛋疼。

是否有类似PHP语言中的:

<?php
$func = "test1";
$result = $func();

这样通过已知的函数名字符串来调用函数的方法?


我自问自答,搜索一番,找到一篇文章讲了一个方法:

在 GOLANG 中用名字调用函数


由于golong中函数也是类型 所以可以这样

package main

import "fmt"

func main(){
     symbol := []func()string{test1,test2, test3}
     for _,v := range symbol{
        fmt.Println( v())
     }
}


func test1() string {
    return "test1"
}

func test2() string {
    return "test2"
}

func test3() string {
    return "test3"
}

要实现s = “test”, $s(), 也就是key=value的方式,所以改造上边symbol为一个map

    symbol := map[string]func()string{"test1":test1, "test2":test2, "test":test3}
    s  := "test1"
    fmt.Println(symbol[s]())

补充: c语言中函数不是这样的类型, 但是任何指针都可以赋值给void* p, 所以可以通过指针数组方式实现

void* (symbol[]) = {test1, test2, test3};
//通过字符串获取下标i 然后调用
//获取下标当然可以用哈希的方式 即 string = $string
int hash(char* str)
{
    ....
    ....
    return i;
}

symbol[hash(“test1”)]() //函数调用
【热门文章】
【热门文章】