Polymorphism in Go
In object-oriented programming, polymorphism allows a single interface to refer to objects of multiple types. Go does not strictly enforce this concept, but it offers alternative ways to achieve similar behavior.
Consider the following code snippet:
type Foo struct { ... } type Bar struct { Foo ... } func getFoo() Foo { return Bar{...} }
As you noticed, in Go, this code raises an error indicating that getFoo() must return an instance of Foo. To achieve a polymorphic behavior, you can utilize interfaces and composition in Go:
package main import "fmt" type Foo interface { printFoo() } type FooImpl struct { } type Bar struct { FooImpl } type Bar2 struct { FooImpl } func (f FooImpl)printFoo(){ fmt.Println("Print Foo Impl") } func getFoo() Foo { return Bar{} } func main() { fmt.Println("Hello, playground") b := getFoo() b.printFoo() }
In this updated example:
This technique provides a way to achieve polymorphism in Go by utilizing interfaces and composition, allowing for a single interface to be used for different concrete types.
The above is the detailed content of How Does Go Implement Polymorphism Without Enforcing It?. For more information, please follow other related articles on the PHP Chinese website!