2017-07-07 133 views
-1

是否使用字符串作爲函數名稱並調用它的方法?使用字符串作爲函數名稱 - golang

我有地圖字符串的函數名
stuff := map[string]string{'keyword','function'}

和使用keyword的時候,我想打電話給function以2個參數
stuff['keyword'](arg1,arg2)

但它給我這個錯誤:

cannot call non-function key (type string) 

有沒有辦法讓我的stringstring地圖,仍然實現這一目標?

+0

您可能需要[函數變量](https://stackoverflow.com/questions/3601796/can-we-have-function-pointers-in-google-go),而不是函數_names_。 – mustaccio

+2

[Golang:從字符串(函數的名稱)指向函數的指針](https://stackoverflow.com/questions/18017979/golang-pointer-to-function-from-string-functions-name) – eugenioy

回答

0

您使用的地圖在語法上不是有效的。你可能想是這樣的:

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

你會然後就可以使用您的字符串鍵從地圖上拉出一個函數,並調用它:

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

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