Home > Backend Development > Golang > How to Retrieve Field Values of Pointers Using Reflection in Go?

How to Retrieve Field Values of Pointers Using Reflection in Go?

Mary-Kate Olsen
Release: 2024-11-09 07:46:02
Original
1048 people have browsed it

How to Retrieve Field Values of Pointers Using Reflection in Go?

Getting Field Values of Pointers Using Reflection

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

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

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

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!

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