Reflect.Value.FieldByName引发恐慌

huangapple go评论81阅读模式
英文:

Reflect.Value.FieldByName causing Panic

问题

当调用反射值的.FieldByName方法时,我遇到了以下错误,具体错误如下:

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

代码如下:

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

我知道这提供的信息不多,但这是我能获取到的所有信息。

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

英文:

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

答案1

得分: 17

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

没有必要取value的地址,然后在该reflect.Value上调用Elem(),这样做会取消刚刚创建的指针。

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

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)

答案2

得分: 4

如果你添加一些println语句,你就能理解发生了什么:

http://play.golang.org/p/-kaz105_En

for _, Value:= range NewMap {
	s := reflect.ValueOf(&Value).Elem()
	println(s.String())
	println(s.Elem().String())
	metric := s.Elem().FieldByName(subvalMetric).Interface()
	fmt.Println(metric)
}

输出:

<*main.Struct1 Value>
<main.Struct1 Value>
abc
英文:

If you add few println you understand what happens:

http://play.golang.org/p/-kaz105_En

for _, Value:= range NewMap {
	s := reflect.ValueOf(&amp;Value).Elem()
	println(s.String())
	println(s.Elem().String())
	metric := s.Elem().FieldByName(subvalMetric).Interface()
	fmt.Println(metric)
}

Output:

&lt;*main.Struct1 Value&gt;
&lt;main.Struct1 Value&gt;
abc

huangapple
  • 本文由 发表于 2014年7月3日 01:34:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/24537525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定