Home > Article > Backend Development > Why Does `reflect.Value.FieldByName` Panic When Used on a Pointer Value?
Reflect.Value.FieldByName Panic Explained
When invoking the .FieldByName method on a reflected value, you may encounter a panic error similar to:
<code class="go">panic: reflect: call of reflect.Value.FieldByName on ptr Value</code>
This error typically occurs when you're using reflect.Value incorrectly.
In the example code provided:
<code class="go">s := reflect.ValueOf(&value).Elem() metric := s.FieldByName(subval.Metric).Interface()</code>
The root of the issue is that value is already a pointer to a struct. By taking the address of &value, you're creating a pointer to pointer. When you then call Elem(), you're dereferencing the pointer to pointer, which isn't necessary.
To resolve this issue, simply use reflect.ValueOf(value).Elem() instead of reflect.ValueOf(&value).Elem(). This will correctly dereference the original pointer, providing you with the actual struct value.
For clarity, below is a modified version of your code:
<code class="go">s := reflect.ValueOf(value).Elem() metric := s.FieldByName(subval.Metric).Interface() fmt.Println(metric)</code>
By using reflect.ValueOf(value).Elem(), you obtain the actual struct value, allowing you to access its fields using s.FieldByName.
The above is the detailed content of Why Does `reflect.Value.FieldByName` Panic When Used on a Pointer Value?. For more information, please follow other related articles on the PHP Chinese website!