How to Iterate Over Struct Fields with Reflection in Go

Iterate over Go struct fields at runtime using the reflect package's ValueOf, Type, and Field methods.

Use the reflect package to iterate over a struct's fields by calling reflect.ValueOf on the struct, then looping through the field count with Type.NumField and accessing each field via FieldByIndex or Field.

import "reflect"

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	v := reflect.ValueOf(p)
	t := v.Type()

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		value := v.Field(i)
		fmt.Printf("%s: %v\n", field.Name, value.Interface())
	}
}