将字符串用作函数名 – golang

huangapple go评论167阅读模式
英文:

use string as function name - golang

问题

有没有办法将字符串用作函数名并调用它?

我有一个将字符串映射到函数名的映射表
stuff := map[string]string{'keyword','function'}

当使用keyword时,我想用两个参数调用function
stuff['keyword'](arg1,arg2)

但是它给我报错:

无法调用非函数键(类型为字符串)

有没有办法保持我的字符串字符串映射,并且仍然实现这个功能?

英文:

Is theere a way to use a string as a function name and call it?

I have a map of strings to function names
stuff := map[string]string{'keyword','function'}

and when the keyword is used, i want to call function with 2 arguments
stuff['keyword'](arg1,arg2)

But it gives me this error:

cannot call non-function key (type string)

Is there a way to keep my string to string map and still achieve this?

答案1

得分: 1

你正在使用的地图在语法上是无效的。你可能想要像这样的东西:

stuff := map[string]func(string, string)

然后,你可以使用字符串键从地图中提取一个函数并调用它:

stuff["keyword"]("foo", "goo")

GoPlay:
https://play.golang.org/p/DNALJOmoiZ

英文:

The map you're using isn't syntactically valid. You probably want something like this:

stuff := map[string]func(string, string)

You would then be able to use your string key to pull out a function from the map and call it:

stuff["keyword"]("foo", "goo")

GoPlay:
https://play.golang.org/p/DNALJOmoiZ

huangapple
  • 本文由 发表于 2017年7月7日 20:53:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44971274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定