I would like to understand the interface type with a simple example of it\'s use in Go (Language).
I read the web documentation, but I don\'t get it.
In this example, I'm using the interface to demonstrate how to achieve polymorphism in Golang.
package main
import(
"fmt"
"math"
)
func main(){
rect := Rectangle{20,50}
cir := Circle{2}
//According to object you passed in getArea method,
// it will change the behaviour and that is called Polymorphism.
fmt.Println("Area of Rectangle =",getArea(rect))
fmt.Println("Area of Circle =",getArea(cir))
}
//Interface Shape with one area method
type Shape interface{
area() float64
}
//Creating Rectangle and Circle type using struct
type Rectangle struct{
height float64
width float64
}
type Circle struct{
radius float64
}
//Receiver function, which implements struct's area methods
func(r Rectangle) area() float64{
return r.height * r.width
}
func(c Circle) area() float64{
return math.Pi * math.Pow(c.radius,2)
}
//passing interface as arguments, which can calculate shape of any mentioned type
//All the struct are tied together because of the Interface.
func getArea(shape Shape) float64{
return shape.area()
}