Polymorphism in Go lang
As you have discovered, Go does not support the traditional object-oriented concept of polymorphism through inheritance. However, there are other ways to achieve similar results using interfaces and composition.
Interface and Composition
In Go, interfaces define contracts that specify the methods a type must implement. Composition allows you to create new types by embedding other types. By combining interfaces and composition, you can achieve a form of polymorphism.
For example, consider the following code:
<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 example:
When you run this code, you will see the following output:
Hello, playground Print Foo Impl
This demonstrates how interfaces and composition can be used to achieve a form of polymorphism in Go. By defining an interface, you can ensure that different types share a common set of methods. By embedding types, you can create new types that combine the capabilities of multiple other types. This allows you to write code that treats different types in a uniform way.
The above is the detailed content of How does Go Achieve Polymorphism without Inheritance?. For more information, please follow other related articles on the PHP Chinese website!