Home > Article > Backend Development > How can I change the pointer type and value of an interface variable using reflection in Go?
Question
How can we change the pointer type and value of a variable defined by an interface using reflection?
Answer
In Go, everything is passed by value, including interfaces. When assigning an interface value, a copy is made, limiting the modification potential.
To modify the value stored in an interface variable, its address must be used. By accessing the variable's address through reflect.ValueOf(&varName).Elem(), we can set a new pointer value into it.
Example
var a fmt.Stringer // Interface variable a = &Greeter{"John"} v := reflect.ValueOf(&a).Elem() // Access variable's address v.Set(reflect.ValueOf(&Greeter2{"Jack"})) // Set new pointer value fmt.Println(a.String()) // Hello2, My name is Jack (Greeter2.String() called)
Key Points
Limitations
The above is the detailed content of How can I change the pointer type and value of an interface variable using reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!