Home > Article > Backend Development > Why Do Go\'s Interface Setter Methods Require Pointers?
Polymorphism in Go: Interface Implementation
While Go does not support traditional polymorphism, interfaces provide a means to achieve a similar effect. However, limitations exist when implementing setter methods.
The Problem
Consider the following code:
type MyInterfacer interface { Get() int Set(i int) } type MyStruct struct { data int } func (this MyStruct) Get() int { return this.data }
Attempting to implement the Set method results in an error:
func (this MyStruct) Set(i int) { this.data = i }
Solution
To circumvent this limitation, the receiver in the Set method must be a pointer, as in:
func (this *MyStruct) Set(i int) { this.data = i }
This allows the method to modify the underlying data, which is reflected in the interface variable.
Corrected Code
The following corrected code works as intended:
type MyInterfacer interface { Get() int Set(i int) } type MyStruct struct { data int } func (this *MyStruct) Get() int { return this.data } func (this *MyStruct) Set(i int) { this.data = i } func main() { s := &MyStruct{123} fmt.Println(s.Get()) s.Set(456) fmt.Println(s.Get()) var mi MyInterfacer = s mi.Set(789) fmt.Println(mi.Get()) }
While not true polymorphism, this technique allows for a similar level of flexibility through interface implementation in Go.
The above is the detailed content of Why Do Go\'s Interface Setter Methods Require Pointers?. For more information, please follow other related articles on the PHP Chinese website!