第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

接口指針的奇怪行為

接口指針的奇怪行為

Go
慕容3067478 2023-05-15 09:43:36
我寫了 3 個類似的函數(shù)來找出 Go 指針反射的一個奇怪行為。package mainimport (    "reflect"    "fmt")var i interface{} = struct {}{}     // i is an interface which points to a structvar ptr *interface{} = &i           // ptr is i's pointerfunc f(x interface{}) {             // print x's underlying value    fmt.Println(reflect.ValueOf(x).Elem())}func main1() {  // f is asking for interface? OK, I'll use the struct's interface    structValue := reflect.ValueOf(ptr).Elem().Elem().Interface()    f(structValue)}func main2() {  // Error? Let me try the struct's pointer    structPtr := reflect.ValueOf(ptr).Elem().Interface()    f(structPtr)}func main3() {  // Why this one could succeed after New() ?    typ := reflect.ValueOf(ptr).Elem().Elem().Type()    newPtr := reflect.New(typ).Elem().Addr().Interface()    f(newPtr)}func main() {    //main1()   // panic: reflect: call of reflect.Value.Elem on struct Value    //main2()   // panic: reflect: call of reflect.Value.Elem on struct Value    main3()     // OK. WHY???}只有 main3 在工作,其他 2 個會 panic。為什么?3 的主要區(qū)別在于它創(chuàng)造了新價值。至于main2,我想ValueOf().Elem().Interface()已經(jīng)重構(gòu)了一個指向的接口struct{}{},只是不明白為什么會失敗。
查看完整描述

1 回答

?
哆啦的時光機(jī)

TA貢獻(xiàn)1779條經(jīng)驗 獲得超6個贊

從 reflect.ValueOf 返回的值包含存儲在參數(shù)中的具體值。如果參數(shù)為 nil,則返回零 reflect.Value。

換句話說,reflect.Value 和傳遞給 reflect.Value 的接口具有相同的基礎(chǔ)值。

如果您更改main1為:main2f

func f(x interface{}) {             // print x's underlying value
    fmt.Println(reflect.ValueOf(x))
}

fin的參數(shù)main3是一個*struct{}. 該函數(shù)f取消引用指針(通過調(diào)用 Elem())并打印struct{}.

可能令人困惑的一點是,reflect.ValueOf(ptr).Elem().Elem().Interface()andreflect.ValueOf(ptr).Elem().Interface()返回一個具有相同具體值的接口。

表達(dá)式reflect.ValueOf(ptr).Elem()是 對應(yīng)的反射值i。對該值的調(diào)用Interface()返回一個具有具體值的接口i。

表達(dá)式是對應(yīng)于具體值的reflect.ValueOf(ptr).Elem().Elem()反映值。對該值的i調(diào)用返回一個包含該具體值的接口。Interface()


查看完整回答
反對 回復(fù) 2023-05-15
  • 1 回答
  • 0 關(guān)注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號