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 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了