我寫了 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
為:main2
f
func f(x interface{}) { // print x's underlying value fmt.Println(reflect.ValueOf(x)) }
f
in的參數(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()
- 1 回答
- 0 關(guān)注
- 136 瀏覽
添加回答
舉報
0/150
提交
取消