Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect.Value.FieldByName causing Panic

Tags:

reflection

go

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

like image 677
Ryan Avatar asked Jul 02 '14 17:07

Ryan


2 Answers

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)
like image 172
JimB Avatar answered Nov 20 '22 01:11

JimB


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
like image 4
fabrizioM Avatar answered Nov 20 '22 02:11

fabrizioM