Home > Backend Development > Golang > How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` in Go?

How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` in Go?

Mary-Kate Olsen
Release: 2024-11-08 11:49:02
Original
237 people have browsed it

How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` in Go?

Calling `reflect.Value.FieldByName() on Pointer Value

In Go, when using reflection with struct pointers, attempting to call reflect.Value.FieldByName() on the struct's pointer value can result in the following error:

reflect: call of reflect.Value.FieldByName on ptr Value
Copy after login

Problem
This error occurs when you try to access a field of a struct value that is being represented as a pointer. Consider the following example:

type Family struct {
  first string
  last string
}
type Person struct {
  name string
  family *Family // Pointer to Family struct
}

func Check(data interface{}) {
  v := reflect.ValueOf(data)
  if v.Kind() == reflect.Struct {
    v = v.FieldByName("family").FieldByName("last")
  }
}
Copy after login

When running this code, the error will occur because the family field is a pointer.

Solution
To resolve this issue, you need to dereference the pointer value using reflect.Indirect() to get the actual struct value before accessing the field:

v = reflect.Indirect(v.FieldByName("family")).FieldByName("last")
Copy after login

With this modification, the code will correctly access the last field of the Family struct, regardless of whether family is a value or a pointer.

Explanation
reflect.Indirect() returns the value that the pointer points to. So, in this case, it returns the Family struct value, which is then accessible via FieldByName().

The above is the detailed content of How to Access Fields in a Struct Pointer using `reflect.Value.FieldByName()` 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