duanou3868 2018-09-01 22:03
浏览 217
已采纳

v.Elem()与Inref(v)传递reflect.New(Type)的结果时

My question is related to this question here:

golang - Elem Vs Indirect in the reflect package

Basically it claims that the expression below is true if someX is a reflect.Value that contains a pointer

reflect.Indirect(reflect.ValueOf(someX)) === reflect.ValueOf(someX).Elem()

If that is the case, then why does my code below crash on the last line?

package main

import (
  "reflect"
  "log"
)

type Person struct {
  Name string

}

func main() {


newitem := reflect.New(reflect.ValueOf(Person{}).Type())

log.Println(reflect.TypeOf(newitem)) // shows reflect.Value
log.Println(newitem.Type().Kind()) // shows it is a ptr

log.Println(reflect.Indirect(reflect.ValueOf(newitem))) // this line does not cause panic
log.Println(reflect.ValueOf(newitem).Elem()) // this line causes panic

}

I've been having a hard time understanding the reflect package in Go, and it is likely I've misunderstood some fundamental aspects of the Go language as denoted in stack overflow questions I've been asking the past week.

  • 写回答

1条回答 默认 最新

  • duanqilupinf67040 2018-09-01 22:58
    关注

    Let's break down the following line:

    log.Println(reflect.ValueOf(newitem).Elem())
    

    The value newItem is a reflect.Value. The expression reflect.ValueOf(newItem) returns a reflect.Value containing a reflect.Value. Because the contained value is not a pointer or interface, the call to Elem() panics.

    The following line does not panic because reflect.Indirect returns its argument if the argument is not a pointer type.

     log.Println(reflect.Indirect(reflect.ValueOf(newitem))) 
    

    The problem is that the application is wrapping reflect.Values with reflect.Values. Use the reflect.Value directly as in the following code:

    log.Println(reflect.Indirect(newitem))
    log.Println(newitem.Elem())
    

    Run it on the Playground!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体