v.Elem()与Inref(v)传递reflect.New(Type)的结果时 [英] v.Elem() Vs Indirect(v) when passing in result of a reflect.New(Type)

查看:746
本文介绍了v.Elem()与Inref(v)传递reflect.New(Type)的结果时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这里的问题有关

My question is related to this question here:

golang-Elem与reflect包中的Indirect

基本上,它声明如果someX是包含指针的reflect.Value,则下面的表达式为true

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

}

我一直很难理解Go中的reflect包,并且可能我误解了Go语言的一些基本方面,正如我上周一直在问的堆栈溢出问题所表明的.

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.

推荐答案

让我们分解以下几行:

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

newItem是reflect.Value.表达式reflect.ValueOf(newItem)返回包含reflect.Valuereflect.Value.由于所包含的值不是指针或接口,因此对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.

以下行不会出现紧急情况,因为如果参数不是指针类型,则reflect.Indirect将返回其参数.

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))) 

问题在于应用程序将reflect.Values与reflect.Values包装在一起.如以下代码所示,直接使用reflect.Value:

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())

在操场上运行!

这篇关于v.Elem()与Inref(v)传递reflect.New(Type)的结果时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆