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)
If you add few println you understand what happens:
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)
}
Output:
<*main.Struct1 Value>
<main.Struct1 Value>
abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With