Reflect.Value.FieldByName Causing Panic
The .FieldByName method of a reflected value generates a panic when called on a pointer Value. The error message, "reflect: call of reflect.Value.FieldByName on ptr Value," is thrown when the provided value is a pointer to a struct rather than the struct itself.
In the code provided, the line "s := reflect.ValueOf(&value).Elem()" creates a pointer to the value struct and then dereferences it using Elem(), which is unnecessary. Instead, to access and modify the struct's fields, use "s := reflect.ValueOf(value).Elem()".
The following corrected code snippet eliminates the panic:
s := reflect.ValueOf(value).Elem() metric := s.FieldByName(subval.Metric).Interface() fmt.Println(metric)
By directly reflecting on the struct's value instead of creating an unnecessary pointer, you can access and manipulate its fields correctly without encountering a panic.
The above is the detailed content of Why does `reflect.Value.FieldByName` panic when called on a pointer value?. For more information, please follow other related articles on the PHP Chinese website!