How to Read and Set Struct Fields with Reflection

Use reflect.ValueOf and FieldByName to read or set struct fields dynamically by name.

Use the reflect package to get a reflect.Value of your struct, then call FieldByName to read or Set to write a field by its name.

import "reflect"

type Person struct {
    Name string
    Age  int
}

p := Person{Name: "Alice", Age: 30}
v := reflect.ValueOf(&p).Elem()

// Read
name := v.FieldByName("Name").String()

// Write
v.FieldByName("Age").SetInt(31)

Note: The struct must be passed as a pointer and the field must be exported (start with an uppercase letter) for Set to work.