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

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

指向具有保存類型的接口的指針

指向具有保存類型的接口的指針

Go
慕婉清6462132 2021-12-06 19:10:12
解釋我的問題的最短方法是代碼:var i interface{} // I can't change it. In fact this is a function,i = Item{10}      // that receives interface{}, that contain object (not pointer to object!)fmt.Printf("%T %v\n", i, i)// fmt.Println(i.(NextValuer).NextVal())  // won't compilei = &ifmt.Printf("%T %v\n", i, i)               // there i is pointer to interface{} (not to Item)// fmt.Println(i.(NextValuer).NextVal())  // panics// fmt.Println(i.(*NextValuer).NextVal()) // won't compile但是,如果我嘗試將指向 Item 的指針設置為 i,則代碼有效:i = &Item{10}fmt.Printf("%T %v\n", i, i)fmt.Println(i.(NextValuer).NextVal())但是我的函數接收對象,而不是指向它的指針。我可以得到它的類型(第一fmt.Printf)。但是當我嘗試創建指向它的指針時,我收到的是指向interface{},而不是指向我的對象 ( Item) 的指針。我可以創建指向這個對象的指針來調用NextVal嗎?或者可能是其他方式來做到這一點
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

永遠不要使用指向接口的指針。如果您需要一個指針來調用帶有指針接收器的方法,則必須將指針放入interface{}.


如果您已經在interface{}要使用指針接收器調用方法的地方擁有值,則需要制作該值的可尋址副本。


你想要完成i = &i的可能是:


item := i.(Item)

i = &item

這將創建原始的可尋址副本Item,然后將指向該副本的指針放入i. 請注意,這永遠無法更改原始 的值Item。


如果您不知道 中可以包含的類型,則可以interface{}使用“reflect”復制該值:


func nextVal(i interface{}) {

    // get the value in i

    v := reflect.ValueOf(i)


    // create a pointer to a new value of the same type as i

    n := reflect.New(v.Type())

    // set the new value with the value of i

    n.Elem().Set(v)


    // Get the new pointer as an interface, and call NextVal

    fmt.Println("NextVal:", n.Interface().(NextValuer).NextVal())


    // this could also be assigned another interface{}

    i = n.Interface()

    nv, ok := i.(NextValuer)

    fmt.Printf("i is a NextValuer: %t\nNextVal: %d\n", ok, nv.NextVal())

}

http://play.golang.org/p/gbO9QGz2Tq


查看完整回答
反對 回復 2021-12-06
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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