Polymorphism in GoLang
Last Updated :
20 Sep, 2023
Polymorphism is the ability of a message to be displayed in more than one form. Polymorphism is considered one of the important features of Object-Oriented Programming and can be achieved during either runtime or compile time. Golang is a light-object-oriented language and supports polymorphism through interfaces only. Let us first understand the interfaces by the following example
Example 1:
Go
package main
import (
"fmt"
)
type Figure interface {
Area() float64
}
type Rectangle struct {
length float64
width float64
}
type Square struct {
side float64
}
func (rect Rectangle) Area() float64 {
area := rect.length * rect.width
return area
}
func (sq Square) Area() float64 {
area := sq.side * sq.side
return area
}
func main() {
rectangle := Rectangle{
length: 10.5 ,
width: 12.25 ,
}
square := Square{
side: 15.0 ,
}
var f1 Figure = rectangle
var f2 Figure = square
fmt.Printf( "Area of rectangle: %.3f unit sq.\n" , f1.Area())
fmt.Printf( "Area of square: %.3f unit sq.\n" , f2.Area())
}
|
Output:
Area of rectangle: 128.625 unit sq.
Area of square: 225.000 unit sq.
Objects of different types are treated in a consistent way, as long as they stick to a single interface, which is the essence of polymorphism. Variable declared in an interface are of interface type. They can take whichever value implements the interface which helps interfaces to achieve polymorphism in the Golang. The following example explains the concept of polymorphism:
Example 2:
Go
package main
import (
"fmt"
)
type Reading interface {
reading_time() int
}
type Book struct {
name string
page_count int
}
type Newspaper struct {
name string
page_count int
}
type Magazine struct {
name string
page_count int
}
func (book Book) reading_time() int {
read_time := 10 * book.page_count
return read_time
}
func (newspaper Newspaper) reading_time() int {
read_time := 30 * newspaper.page_count
return read_time
}
func (magazine Magazine) reading_time() int {
read_time := 5 * magazine.page_count
return read_time
}
func calcReadingTime(ReadingTime []Reading) int {
totalTime := 0
for _, t := range ReadingTime {
totalTime += t.reading_time()
}
return totalTime
}
func main() {
book1 := Book{
name: "Goosebumps" ,
page_count: 150 ,
}
newspaper1 := Newspaper{
name: "TOI" ,
page_count: 12 ,
}
magazine1 := Magazine{
name: "Forbes" ,
page_count: 40 ,
}
ReadingTime := []Reading{book1, newspaper1, magazine1}
totalTime := calcReadingTime(ReadingTime)
fmt.Printf( "Total Time is %d minutes.\n" , totalTime)
}
|
Output:
Total Time is 2060 minutes.
Share your thoughts in the comments
Please Login to comment...