In this article, we'll explore an issue faced when attempting to retrieve field values of a struct that contains a pointer to another struct.
Consider this example:
type Family struct { first string last string } type Person struct { name string family *Family }
Imagine we have a Person with a pointer to Family. We want to access the last field of Family using reflection. The following code would fail with an error:
func Check(data interface{}) { var v = reflect.ValueOf(data) if v.Kind() == reflect.Struct { fmt.Println("was a struct") v = v.FieldByName("family").FieldByName("last") fmt.Println(v) } }
The error encountered is:
reflect: call of reflect.Value.FieldByName on ptr Value
The reason for this error is that we are trying to call .FieldByName("family") on a reflect.Value that represents a pointer, rather than the value it points to.
To fix this issue, we need to first indirect the pointer value before calling .FieldByName(). The corrected code would look like this:
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) } }
By indirectly dereferencing the pointer value using reflect.Indirect(), we can access the underlying value and then retrieve the last field using .FieldByName().
The above is the detailed content of How to Retrieve Field Values of Pointers Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!