Retrieving Struct Field Names with Reflection
In Go's reflection capabilities, one can introspect an arbitrary struct using the reflect package. However, a common question arises: how to obtain the name of a struct field?
Consider the following 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()) // Prints "string" }
In this example, the goal is to print "Foo" using reflection. However, the code currently prints "string". Why is this happening?
The answer lies in the reflect package's methods:
To obtain the field name, we must first get the reflect.Value for the struct itself. We can do this by dereferencing the pointer to the struct and getting its reflect.Value using reflect.ValueOf.
Next, we need to retrieve the reflect.Value for the first field of the struct. We can do this using val.Field(0).
Finally, we can get the reflect.Type of the field using val.Field(0).Type(). To get the field name, we can then call val.Field(0).Type().Name().
Therefore, the modified code below will correctly print "Foo":
fmt.Println(val.Field(0).Type().Field(0).Name())
The above is the detailed content of How to Retrieve a Struct Field's Name Using Go Reflection?. For more information, please follow other related articles on the PHP Chinese website!