Home > Article > Backend Development > Can You Change the Pointer Type and Value of a Variable Defined by an Interface Using Reflection in Go?
Changing Pointer Type and Value Under Interface with Reflection
In Go, interfaces represent contracts that define specific methods, but do not specify the type of the underlying object. This flexibility allows for dynamic binding, but can also pose challenges when attempting to modify the pointer type and value of a variable defined by an interface.
Can Pointer Type and Value Be Changed Under an Interface?
Changing the pointer value under an interface is possible using reflection. By setting the element of the reflection value to the element of the new pointer value, the value can be modified. However, changing the pointer type is not directly possible.
Using Reflection to Change Pointer Value
To change the pointer value of a variable defined by an interface, follow these steps:
Example
In the following code, the value of a is modified using reflection to point to a Greeter2 object while also updating the name to "Jack":
package main import ( "fmt" "reflect" ) type Greeter struct { Name string } func (g *Greeter) String() string { return "Hello, My name is " + g.Name } type Greeter2 struct { Name string } func (g *Greeter2) String() string { return "Hello2, My name is " + g.Name } func main() { var a fmt.Stringer a = &Greeter{"John"} fmt.Println(a.String()) // Output: Hello, My name is John v := reflect.ValueOf(&a).Elem() v.Set(reflect.ValueOf(&Greeter2{"Jack"}).Elem()) fmt.Println(a.String()) // Output: Hello2, My name is Jack }
Note: To modify the pointer type of a variable, it must be passed by address. This is because Go passes values by copy, and only pointers allow the pointed value to be modified indirectly.
The above is the detailed content of Can You Change the Pointer Type and Value of a Variable Defined by an Interface Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!