To iterate through the fields of a struct in Go using reflection, you can use the reflect
package. Here's an example:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
Address string
}
func main() {
person := Person{
Name: "John Doe",
Age: 25,
Address: "123 Main St",
}
// Get the reflect.Value of the struct
v := reflect.ValueOf(person)
// Iterate through the fields of the struct
for i := 0; i < v.NumField(); i++ {
// Get the field name and value
field := v.Field(i)
fieldName := v.Type().Field(i).Name
// Print the field name and value
fmt.Printf("%s: %v\n", fieldName, field.Interface())
}
}
In this example, we define a Person
struct with three fields: Name
, Age
, and Address
. We then create an instance of the Person
struct and use reflect.ValueOf()
to get the reflect.Value
of the struct.
Next, we use NumField()
to get the number of fields in the struct. Then, we iterate through the fields using a for loop, accessing each field using Field(i)
. We also use Type().Field(i).Name
to get the name of the field.
Finally, we use field.Interface()
to obtain the value of the field as an interface{}
and print the field name and value.
The output of this example will be:
Name: John Doe
Age: 25
Address: 123 Main St
Note that this method relies on the fields being public in order to access them using reflection. Private fields cannot be accessed this way.