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!

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

报告相同问题?

悬赏问题

  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包