Home >Backend Development >Golang >How Can I Modify a Struct's Field via an Interface Method Using Pointer Receivers in Go?
Pointer receiver for Golang methods
In Golang, a receiver refers to an object responsible for handling method calls. According to the type of receiver, it can be divided into value receiver and pointer receiver.
In the given example, the receiver of the SetSomeField method is a value receiver, which means that the method operates on a copy of the variable created when the method was called. This results in the method being unable to modify the actual instance but only updating the copy, leading to unexpected behavior.
In order to solve this problem, the receiver of the SetSomeField method needs to be changed to a pointer receiver. Pointer receivers allow methods to modify the actual instance because they directly access the instance's memory address.
However, this will create a new problem: the structure no longer implements the interface. This is because the interface requires the SetSomeField method to be defined as a value receiver, and pointer receivers are not compatible.
The solution is to create a Create function that returns a pointer receiver type and then assign this pointer to a variable that implements the interface. This allows methods to modify the actual instance while still conforming to the interface definition:
package main import ( "fmt" ) type IFace interface { SetSomeField(newValue string) GetSomeField() string } type Implementation struct { someField string } func (i *Implementation) GetSomeField() string { return i.someField } func (i *Implementation) SetSomeField(newValue string) { i.someField = newValue } func Create() *Implementation { return &Implementation{someField: "Hello"} } func main() { var a IFace a = Create() a.SetSomeField("World") fmt.Println(a.GetSomeField()) }
By using a pointer receiver, the SetSomeField method can modify the actual instance while still implementing the interface. This ensures that the method modifies the object's state as expected.
The above is the detailed content of How Can I Modify a Struct's Field via an Interface Method Using Pointer Receivers in Go?. For more information, please follow other related articles on the PHP Chinese website!