Golang Method with Pointer Receiver
When attempting to modify the value of an instance through a method, it's crucial to understand the concept of pointer receivers. In this example, the SetSomeField method is not working as expected because its receiver is not of pointer type.
To rectify this, we modify the SetSomeField method to accept a pointer receiver as follows:
func (i *Implementation) SetSomeField(newValue string) { ... }
However, this change introduces a new problem: the struct no longer implements the interface because the GetSomeField method still has a value receiver.
The solution lies in using a pointer to the struct when implementing the interface. By doing so, we enable the method to modify the actual instance without creating a copy. Here's the modified code:
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()) }
In this updated code, the Create function returns a pointer to the Implementation struct, which implements the IFace interface. Consequently, the a variable of type IFace can refer to the pointer to the Implementation struct, allowing the SetSomeField method to modify its value.
The above is the detailed content of Why Doesn't My Go Method Modify the Instance Value Unless I Use a Pointer Receiver?. For more information, please follow other related articles on the PHP Chinese website!