导致恐慌的Reflect.Value.FieldByName [英] Reflect.Value.FieldByName causing Panic

查看:2711
本文介绍了导致恐慌的Reflect.Value.FieldByName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用反射值的.FieldByName方法时出现以下错误,确切的错误是: -
$ b $

  panic:reflect:在ptr上调用reflect.Value.FieldByName Value 

,代码如下: -

  s:= reflect.ValueOf(& value).Elem()(value是一个结构)
metric := s.FieldByName(subval.Metric).Interface()(subval.Metric是一个字符串)

我知道这并不多,但这是我可以得到的所有信息。



以下是Go Playground上代码的链接: http://play.golang.org/p/E038cPOoGp

解决方案

您的已经是一个指向结构体的指针。尝试在代码中打印 s.Kind()



没有理由将 value ,然后在 reflect.Value 上调用 Elem()
$ b

  s:= reflect.ValueOf(value).Elem()
metric := s.FieldByName(subvalMetric).Interface()
fmt.Println(metric)


I'm getting the following error when calling the .FieldByName method of a reflected value, the exact error is :-

panic: reflect: call of reflect.Value.FieldByName on ptr Value

and the code is :-

s := reflect.ValueOf(&value).Elem() (value is a struct)
metric := s.FieldByName(subval.Metric).Interface() (subval.Metric is a string)

I understand this isn't much, but this is all the information I can get.

Here's a link to the code on Go Playground: http://play.golang.org/p/E038cPOoGp

解决方案

Your value is already a pointer to a struct. Try printing out s.Kind() in your code.

There's no reason to take the address of value, then call Elem() on that reflect.Value, which dereferences the pointer you just created.

s := reflect.ValueOf(value).Elem()
metric := s.FieldByName(subvalMetric).Interface()
fmt.Println(metric)

这篇关于导致恐慌的Reflect.Value.FieldByName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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