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

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

接口指針的奇怪行為

接口指針的奇怪行為

Go
慕容3067478 2023-05-15 09:43:36
我寫了 3 個類似的函數來找出 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 的主要區別在于它創造了新價值。至于main2,我想ValueOf().Elem().Interface()已經重構了一個指向的接口struct{}{},只是不明白為什么會失敗。
查看完整描述

1 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

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

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

如果您更改main1為:main2f

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

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

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

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

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


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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