In object-oriented programming, polymorphism allows objects to exhibit different behaviors based on their class. But in Go, the concept of polymorphism is not implemented in the traditional sense. Let's delve into the reasons behind this and explore how to achieve similar functionality in Go.
Go is not a traditional object-oriented language. It adopts a different approach by using:
Unlike in object-oriented languages, Go does not support method overriding or virtual methods. This allows Go to maintain a higher level of type safety.
To achieve polymorphism-like behavior in Go, we can employ the following techniques:
Example:
package main
import "fmt"
// Common interface
type Foo interface {
printFoo()
}
// Derived type with unique implementation
type FooImpl struct{}
func (f FooImpl) printFoo() {
fmt.Println("Print Foo Impl")
}
// Derived type composed using the common interface
type Bar struct {
FooImpl
}
// Function returning the common interface
func getFoo() Foo {
return Bar{}
}
func main() {
fmt.Println("Hello, playground")
b := getFoo()
b.printFoo()
}
In this example, Foo is the common interface, FooImpl is the derived type with its own implementation, and Bar is a derived type composed using FooImpl. The getFoo() function returns an instance of the Foo interface, allowing us to treat different derived types as one interface type.
This approach provides a form of polymorphism in Go by enabling us to handle different derived types as instances of a common interface.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3