Polymorphism in Go: Does It Exist?
Polymorphism, the ability for objects of different classes to have identical methods, is a fundamental aspect of object-oriented programming. In Go, however, setter methods for interfaces appear to be unavailable.
Let's examine a basic example:
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 }
When this code is run, the Set method for the MyStruct type fails because the receiver is not a pointer. Any changes made to this are lost when the function exits.
One might attempt to fix this by changing the receiver to a pointer:
func (this *MyStruct) Set(i int) { this.data = i }
However, this would result in a compilation error. Interface methods in Go cannot have pointer receivers.
So, is there any way to achieve polymorphism in this scenario?
The closest alternative is to use an interface type and an anonymous struct that implements the interface:
type MyInterfacer interface { Get() int Set(i int) } var mi MyInterfacer = &MyStruct{123} fmt.Println(mi.Get()) // prints 123 mi.Set(456) fmt.Println(mi.Get()) // prints 456
While this solution is not true polymorphism, it utilizes an interface to provide a clean and flexible way to manipulate objects of different types.
The above is the detailed content of Does Go Support Polymorphism: Finding Workarounds for Setter Methods?. For more information, please follow other related articles on the PHP Chinese website!