Home  >  Article  >  Backend Development  >  How to Access Fields in a Struct Through a Pointer Using Reflection in Go?

How to Access Fields in a Struct Through a Pointer Using Reflection in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 01:15:02766browse

How to Access Fields in a Struct Through a Pointer Using Reflection in Go?

reflect: Addressing the Pointer Error in FieldByName

In the provided code, we attempt to access the "last" field of a "Family" struct using reflection. However, the "family" field is a pointer, and accessing its "last" field directly using "FieldByName" results in an error:

reflect: call of reflect.Value.FieldByName on ptr Value

To address this, we need to first dereference the pointer to access the actual value of the struct. This can be achieved using the "Indirect" function from the "reflect" package.

Here's the modified code:

familyPtr := v.FieldByName("family")
v = reflect.Indirect(familyPtr).FieldByName("last")

In this code, we first retrieve the reflect.Value of the "family" field using "FieldByName". Then, we use "Indirect" to dereference the pointer and obtain the actual value of the "Family" struct. Finally, we can access the "last" field using "FieldByName" on the dereferenced value.

By following this approach, we can access the "last" field of the "Family" struct even when it is accessed through a pointer reference.

The above is the detailed content of How to Access Fields in a Struct Through a Pointer Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn