Home > Backend Development > Golang > 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
Release: 2024-11-09 01:15:02
Original
847 people have browsed it

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
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template