Home > Backend Development > Golang > How Can I Retrieve a Struct Field Name Using Go Reflection?

How Can I Retrieve a Struct Field Name Using Go Reflection?

Barbara Streisand
Release: 2024-12-10 14:44:10
Original
258 people have browsed it

How Can I Retrieve a Struct Field Name Using Go Reflection?

Retrieving Struct Field Name Using Reflection

Problem Statement:

Consider the following Golang code:

type A struct {
    Foo string
}

func (a *A) PrintFoo() {
    fmt.Println("Foo value is " + a.Foo)
}

func main() {
    a := &A{Foo: "afoo"}
    val := reflect.Indirect(reflect.ValueOf(a))
    fmt.Println(val.Field(0).Type().Name())
}
Copy after login

In this example, the code prints "string", not "Foo". How can we retrieve the field name "Foo" using reflection in this context?

Answer:

To retrieve the field name, use the Type().Field(0).Name method on the reflect.Value. This method returns the name of the field's type, which in this case is "Foo". The following corrected code demonstrates this:

fmt.Println(val.Type().Field(0).Name()) // Prints "Foo"
Copy after login

Explanation:

The Indirect function dereferences the pointer a. The Type().Field(0) method retrieves the struct field information for the first field, and Name() extracts the field name. Note that there is no way to retrieve the field name for a reflect.Value directly, since this information is associated with the containing struct.

The above is the detailed content of How Can I Retrieve a Struct Field Name Using Go Reflection?. 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