How to Access Fields of a Pointed Struct Using Reflection in Go?

Susan Sarandon
Release: 2024-11-08 04:36:02
Original
779 people have browsed it

How to Access Fields of a Pointed Struct Using Reflection in Go?

Dealing with Pointer Values in Reflect: Resolving "reflect: call of reflect.Value.FieldByName on ptr Value" Errors

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")
Copy after login
  • familyPtr retrieves the reflect.Value of the family field.
  • Indirect(familyPtr) dereferences the pointer, resulting in the actual Family value.
  • FieldByName("last") then retrieves the "last" field from the dereferenced Family value.

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!