简体   繁体   中英

Reflect.Value.FieldByName causing Panic

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM