How to reflectively access and modify private fields of a struct in Golang?

To reflectively access and modify private fields of a struct in Golang, you can use the reflect package, which allows for runtime introspection and manipulation of types.

Here's an example of how to use reflection to access and modify private fields of a struct:

package main import ( "fmt" "reflect" ) type person struct { name string age int height int } func main() { p := person{ name: "John Doe", age: 30, height: 180, } // Accessing private fields using reflection v := reflect.ValueOf(p) field := v.FieldByName("name") if field.IsValid() && field.CanInterface() { fmt.Println(field.Interface()) } // Modifying private fields using reflection if field.CanSet() { field.SetString("Jane Doe") fmt.Println(p.name) } }

In this example, we have a person struct with private fields (name, age, and height).

To access private fields reflectively, we use reflect.ValueOf() to get a reflect.Value for the struct, and then use FieldByName() to get the reflect.Value of the private field by its name. We can then use methods like IsValid() and CanInterface() to check if the field is valid and can be accessed. Finally, we can use the Interface() method to get the value of the field.

To modify private fields reflectively, we need to make sure the field is settable by checking CanSet(). If it is, we can use methods like SetString() (for a string field) to modify the field's value.

Note: Reflective access and modification should be used with caution as it bypasses the safety provided by the Go type system, and may impact performance. It's generally recommended to favor direct field access whenever possible.