In the provided code, the data structure you've defined includes a struct Family, which is stored as a pointer in the Person struct. When trying to access fields within the pointed Family using the reflect package, you encounter the error "reflect: call of reflect.Value.FieldByName on ptr Value."
Understanding the Error
This error occurs because the FieldByName function of the reflect package expects a non-pointer value as its input. When you use a pointer (*Family) as the receiver of FieldByName, the function attempts to access the pointer itself instead of the value it points to.
Resolving the Issue
To resolve this issue, you need to indirect the pointer before accessing the fields. This can be done using the Indirect function of the reflect package:
familyPtr := v.FieldByName("family") v = reflect.Indirect(familyPtr).FieldByName("last")
Updated Code
Here's the updated code that correctly handles the pointer value:
func Check(data interface{}) { var v = reflect.ValueOf(data) if v.Kind() == reflect.Struct { fmt.Println("was a struct") familyPtr := v.FieldByName("family") v = reflect.Indirect(familyPtr).FieldByName("last") fmt.Println(v) } }
The above is the detailed content of How to Access Fields of a Pointed Struct Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!