英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论