15

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

2
  • the error message is pretty clear. Can you make a runnable example in the playground? (and value may be a struct, &value is a pointer)
    – JimB
    Commented Jul 2, 2014 at 17:37
  • Updated the main post with a link to the code in the playground (play.golang.org/p/E038cPOoGp)
    – Ryan
    Commented Jul 2, 2014 at 17:59

2 Answers 2

17

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)
1
  • 17
    I'd personally replace s := reflect.ValueOf(value).Elem() with s := reflect.Indirect(reflect.ValueOf(value)), that way the same code will work on both structs and pointers to structs. reflect.Indirect
    – OneOfOne
    Commented Jul 2, 2014 at 18:28
4

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.