How to get and set the value of a struct field using reflection in Golang?

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:

  1. Import the reflect package:
import ( "reflect" )
  1. Define a struct type:
type Person struct { Name string Age int }
  1. Create an instance of the struct:
p := Person{Name: "John", Age: 30}
  1. Get the value of a field using reflection:
fieldValue := reflect.ValueOf(p).FieldByName("Name").Interface()
  1. Set the value of a field using reflection:
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.