转到功能图
我有一个定义了函数的 Go 程序。我还有一张地图,每个功能都应该有一个键。我怎样才能做到这一点?
我已经尝试过这个,但这不起作用。
func a(param string) { } m := map[string] func { 'a_func': a, } for key, value := range m { if key == 'a_func' { value(param) } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你想做这样的事情吗?我修改了示例以使用不同类型和数量的函数参数。
Are you trying to do something like this? I've revised the example to use varying types and numbers of function parameters.
如果您知道签名(并且所有函数都具有相同的签名),则可以使用
我认为这比使用接口{}更干净/更安全
Works if you know the signature (and all the funcs have the same signature)
I think this is cleaner/safer than using interface{}
如果函数是相同的接口,则可以定义类型。
You can define a type if functions are same interface.
@Seth Hoenig 的回答对我帮助最大,但我只是想补充一点,Go 也接受具有定义返回值的函数:
如果你认为它很难看,你可以随时使用类型(请参阅 >@smagch 的回答)。
@Seth Hoenig's answer helped me best, but I just wanted to add that Go accepts functions with defined return value as well:
If you think it's ugly, you could always use a type (see @smagch's answer).
希望这对您有用(您可以使用interface{}代替任何)
Hope this works for you(you can use interface{} instead any)
以下是我在我的案例中的工作方式:
https://play.golang.org/p/ 8_g6Di1OKZS
Here is the way I made it work in my case:
https://play.golang.org/p/8_g6Di1OKZS
我使用了 map[string]func (a type, b *type) 我传递了一个字符串来搜索地图,并传递了一个指针来修改切片。
希望有帮助!
I used a map[string]func (a type, b *type) I passed a string to search the map and a pointer to modify the slice.
Hope that helps!