Polymorphism in Go lang: Achieving Through Interfaces and Composition
Polymorphism, a fundamental concept in object-oriented programming, allows objects to behave differently based on their class or type. In Go, unlike traditional OO languages, polymorphism is achieved through interfaces and composition.
Problem:
An attempt to implement polymorphism in Go using structural inheritance like the following code snippet would result in an error:
<code class="go">type Foo struct { ... } type Bar struct { Foo ... } func getFoo() Foo { return Bar{...} }</code>
Solution:
In Go, polymorphism is achieved through interfaces and composition. An interface defines a set of methods that a type must implement, allowing the type to be used polymorphically anywhere the interface is expected.
The code below demonstrates how polymorphism can be achieved in Go using interfaces and composition:
<code class="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() }</code>
In this code snippet:
By utilizing interfaces and composition, Go provides a flexible and efficient approach to achieving polymorphism without the need for traditional inheritance.
The above is the detailed content of How Can Polymorphism be Achieved in Go Without Traditional Inheritance?. For more information, please follow other related articles on the PHP Chinese website!