Polymorphism in Go: Decoding the Setter Conundrum
In the realm of object-oriented programming, polymorphism enables objects of different classes to be treated as instances of a common super-type. However, in Go, the question arises: does polymorphism exist and, if so, how does it manifest?
Consider the following Go code, where an attempt is made to create an interface with getter and setter methods:
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 }
However, the setter method encounters an issue: the receiver this MyStruct is not a pointer, resulting in any changes made within the method being lost once it exits. Moreover, making the receiver this *MyStruct would hinder compilation.
To address this, a corrected version of the code utilizes pointers:
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 }
By introducing pointers, we enable changes made within the setter method to persist beyond its scope. While this technique may not constitute strict polymorphism in the traditional sense, it adheres to sound Go practices and provides a viable solution to the initial issue.
The above is the detailed content of How Can Polymorphism Be Achieved with Setters in Go?. For more information, please follow other related articles on the PHP Chinese website!