package main import ( "fmt" "reflect" ) func main() { var x int = 42 reflect.ValueOf(&x).Elem().SetInt(20) fmt.Println(x) // Output: 20 }
package main import ( "fmt" "reflect" ) type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 25} reflect.ValueOf(&p).Elem().FieldByName("Age").SetInt(30) fmt.Println(p) // Output: {Alice 30} }In this example, we define a struct type Person with two fields, Name and Age. We create an instance of this struct and set its values to "Alice" and 25. Then, we use reflect.ValueOf() to get a reflect.Value object representing a pointer to p. We call .Elem() on that object to get the reflect.Value object representing p itself. Finally, we call .FieldByName() on that object to get the reflect.Value object representing the Age field, and then call .SetInt() on that object to set its value to 30. The reflect package is part of the Go standard library.