先看一个示例代码:
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();
这样通过已知的函数名字符串来调用函数的方法?