我有這個完美運行的代碼:package mainimport ( "fmt")var funcMap = map[string]interface{}{ "hello": hello,}func main() { callDynamically("hello")}func callDynamically(name string) { funcMap[name].(func())()}func hello() { fmt.Println("hello")}但是如果我嘗試hello()像這樣定義我的結構類型,我的大腦會發瘋:package mainimport ( "fmt")type myType struct { field1 string field2 string funcMap map[string]interface{}}func main() { mt := &myType{ field1: "qwe", field2: "asd", funcMap: map[string]interface{}{ "hello": (*myType).hello, }, } mt.callDynamically("hello")}func (mt *myType) callDynamically(name string) { mt.funcMap[name].(func())()}func (mt *myType) hello() { fmt.Println("hello")}https://play.golang.org/p/pPvmaL22_Td我收到了這個錯誤:panic: interface conversion: interface {} is func(*main.myType), not func()func()當我的函數在callDynamically自定義結構類型上定義時,我真的不明白如何調用。有什么幫助嗎?謝謝你。
2 回答
ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
Go 中的方法只是一個添加了一些語法糖的函數。接收者實際上是函數的第一個參數,因此(*myType).hello- 來自類型的方法 - 實際上是func(*myType); 它沒有要調用的接收器實例,因此如果不顯式提供一個作為函數參數,就無法調用它。這在 Method Expressions 的規范中有所介紹。
如果您改為從該類型的實例中獲取方法,則該參數將已被填充,因此:
foo := &myType{}
fn := foo.hello這fn是func()因為它已經有一個實例可以用作接收器。這在 Method Values 的規范中有所介紹。
一只甜甜圈
TA貢獻1836條經驗 獲得超5個贊
初始化后添加struct實例函數:funcMapstruct
func main() {
mt := &myType{
field1: "qwe",
field2: "asd",
funcMap: map[string]interface{}{},
}
mt.funcMap["hello"] = mt.hello
mt.callDynamically("hello")
}
- 2 回答
- 0 關注
- 202 瀏覽
添加回答
舉報
0/150
提交
取消
