Golang:指向函数的字符串(函数的名称) [英] Golang: pointer to function from string (function's name)

查看:85
本文介绍了Golang:指向函数的字符串(函数的名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有机会从函数的名字得到指向函数的指针,呈现为字符串?这需要例如将一些函数作为参数发送给另一个函数。一些元编程,你知道。

Is there any chance to get pointer to function from function's name, presented as string? This needed for example to send some function as argument to another function. Some sort of metaprogramming, you know.

谢谢!

Thanks!

推荐答案

Go功能是一流的价值。您不需要从动态语言恢复到可怜的技巧。

Go functions are first class values. You don't need to revert to the poor tricks from dynamic languages.

package main

import "fmt"

func someFunction1(a, b int) int {
        return a + b
}

func someFunction2(a, b int) int {
        return a - b
}

func someOtherFunction(a, b int, f func(int, int) int) int {
        return f(a, b)
}

func main() {
        fmt.Println(someOtherFunction(111, 12, someFunction1))
        fmt.Println(someOtherFunction(111, 12, someFunction2))
}

Playground

输出:

123
99

如果函数的选择取决于仅运行时已知的值,则可以使用映射:

If the selection of the function depends on some run-time-only known value, you can use a map:

m := map[string]func(int, int) int {
        "someFunction1": someFunction1,
        "someFunction2": someFunction2,
}

...

z := someOtherFunction(x, y, m[key])

这篇关于Golang:指向函数的字符串(函数的名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆