Home > Article > Backend Development > How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` in Go?
Calling `reflect.Value.FieldByName() on Pointer Value
In Go, when using reflection with struct pointers, attempting to call reflect.Value.FieldByName() on the struct's pointer value can result in the following error:
reflect: call of reflect.Value.FieldByName on ptr Value
Problem
This error occurs when you try to access a field of a struct value that is being represented as a pointer. Consider the following example:
type Family struct { first string last string } type Person struct { name string family *Family // Pointer to Family struct } func Check(data interface{}) { v := reflect.ValueOf(data) if v.Kind() == reflect.Struct { v = v.FieldByName("family").FieldByName("last") } }
When running this code, the error will occur because the family field is a pointer.
Solution
To resolve this issue, you need to dereference the pointer value using reflect.Indirect() to get the actual struct value before accessing the field:
v = reflect.Indirect(v.FieldByName("family")).FieldByName("last")
With this modification, the code will correctly access the last field of the Family struct, regardless of whether family is a value or a pointer.
Explanation
reflect.Indirect() returns the value that the pointer points to. So, in this case, it returns the Family struct value, which is then accessible via FieldByName().
The above is the detailed content of How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` in Go?. For more information, please follow other related articles on the PHP Chinese website!