亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

func() 在自定義結構類型上時的接口轉換

func() 在自定義結構類型上時的接口轉換

Go
開心每一天1111 2022-06-13 10:38:38
我有這個完美運行的代碼: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

fnfunc()因為它已經有一個實例可以用作接收器。這在 Method Values 的規范中有所介紹。


查看完整回答
反對 回復 2022-06-13
?
一只甜甜圈

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")

}


查看完整回答
反對 回復 2022-06-13
  • 2 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號