Reflect.Value.FieldByName引发恐慌

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

Reflect.Value.FieldByName causing Panic

问题

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

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

代码如下:

  1. s := reflect.ValueOf(&value).Elem()(value是一个结构体)
  2. 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 :-

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

and the code is :-

  1. s := reflect.ValueOf(&value).Elem() (value is a struct)
  2. 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(),这样做会取消刚刚创建的指针。

  1. s := reflect.ValueOf(value).Elem()
  2. metric := s.FieldByName(subvalMetric).Interface()
  3. 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.

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

答案2

得分: 4

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

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

  1. for _, Value:= range NewMap {
  2. s := reflect.ValueOf(&Value).Elem()
  3. println(s.String())
  4. println(s.Elem().String())
  5. metric := s.Elem().FieldByName(subvalMetric).Interface()
  6. fmt.Println(metric)
  7. }

输出:

  1. <*main.Struct1 Value>
  2. <main.Struct1 Value>
  3. abc
英文:

If you add few println you understand what happens:

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

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

Output:

  1. &lt;*main.Struct1 Value&gt;
  2. &lt;main.Struct1 Value&gt;
  3. 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:

确定