type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 30} v := reflect.ValueOf(p) if v.FieldByName("Name").CanSet() { v.FieldByName("Name").SetString("Bob") } fmt.Println(p.Name) // Output: Bob }
func main() { s := []int{1, 2, 3} v := reflect.ValueOf(s) if v.Index(0).CanSet() { v.Index(0).SetInt(4) } fmt.Println(s) // Output: [4 2 3] }In this example, we create a slice of integers and get a `reflect.Value` object representing it. We then call the `Index` method on the `reflect.Value` object to get a `reflect.Value` object representing the first element of the slice. We then call the `CanSet` method on the element value to check if it can be set (which it can). We then use the `SetInt` method to change the value of the first element to 4. Package library: `reflect`.