Home  >  Article  >  Backend Development  >  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
Mary-Kate OlsenOriginal
2024-11-09 07:46:021008browse

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
}

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)
    }
}

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)
    }
}

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!

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