To get and set the value of a struct field using reflection in Go, you can use the reflect
package. Here's an example of how to do it:
import (
"reflect"
)
type Person struct {
Name string
Age int
}
p := Person{Name: "John", Age: 30}
fieldValue := reflect.ValueOf(p).FieldByName("Name").Interface()
reflect.ValueOf(&p).Elem().FieldByName("Name").SetString("Jane")
In the example above, we first use reflect.ValueOf
to get a reflect.Value
representing the struct p
. We then use the FieldByName
method to get a reflect.Value
representing the field we want to get or set. Finally, we use the appropriate methods like Interface()
or SetString()
to perform the desired action.
Note that when setting the value of a field, you need to use the reflect.Value
obtained from reflect.ValueOf
and call Elem()
on it, since we want to modify the actual struct value and not a copy of it.