Example of polymorphism in Go
package main
import "fmt"
type Cat interface {
Meow()
}
type Persian struct {
CatType string
}
func (d Persian) Meow() {
fmt.Println("Persian Cat’s Sound")
}
func MakeCatMeow(d Persian) {
d.Meow()
}
func main() {
d := Persian{"Jack"}
MakeCatMeow(d)
}
Output:
Persian Cat’s Sound
Program Exited.
Explanation:
In the above code, the struct Persian implements the Cat interface. Thus the struct becomes the type Cat so that it can be passed in that function. Any type is then added and implemented as an interface. This is polymorphism. We can see here that an object takes many different forms.
Types of Polymorphism
Runtime Polymorphism
When a call is resolved at runtime it is referred to as runtime polymorphism. This is achieved in the Go language through interfaces. Suppose the same function calc is used in different contexts to calculate bills. When the compiler sees this call it delays which exact method to be called at run time. This is where runtime polymorphism occurs.
Compile-time Polymorphism
When the call is resolved during compile time it is referred to as compile-time polymorphism. Some of the types of compile-time polymorphism are:
- Method/Function Overloading: More than one function exists with the same name but with different return types.
- Operator Overloading: On different data types, the same operator is used to operate.
Note: In GO language, we can only implement the Runtime Polymorphism.
Uses of Polymorphism
Polymorphism is used to reduce the code and coupling in a program as a single object is used to perform multiple functions. It is an important concept in OO-Programming and is heavily used. It enables programmers to re-use the codes via Polymorphism. And it also supports a single variable name for multiple data types.
Check out this article - Compile Time Polymorphism
Know What is Object in OOPs here in detail.
FAQs
-
What is polymorphism?
Polymorphism is one of the properties of Object-Oriented Programming. When an object behaves like another, it is said to be reflecting Polymorphism.
-
How is polymorphism implemented in the Go language?
Polymorphism is achieved through interfaces in Go. Variables declared in an interface are of interface type so that the above-mentioned is implemented.
-
Why do we use polymorphism?
We use polymorphism to reduce the code. The coupling is also reduced with the help of polymorphism.
Key Takeaways
In this article, we have extensively discussed the following things:
- What are polymorphism and object-oriented programming?
- How polymorphism is implemented in Go language.
- Uses of polymorphism.
- Types of polymorphism in Golang.
We hope that this blog has helped you enhance your knowledge regarding Polymorphism in the GO language and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!