shapes-using-interfaces example
Calculating the area and perimeter of circles, rectangles and
triangles using functions.
This example is done using,
GitHub Webpage
OVERVIEW
You can see the function and methods are basically the same thing. But when
we use interfaces we can give a function the type (struct) and the interface
will figure it out.
As we go from,
// Get the shape properties
c1Area := circleArea(c1)
c1Perimeter := circlePerimeter(c1)
r1Area := rectangleArea(r1)
r1Perimeter := rectanglePerimeter(r1)
t1Area := triangleArea(t1)
t1Perimeter := trianglePerimeter(t1)
To a simple form,
// Get the shape properties
c1Area := area(c1)
c1Perimeter := perimeter(c1)
r1Area := area(r1)
r1Perimeter := perimeter(r1)
t1Area := area(t1)
t1Perimeter := perimeter(t1)
We can clearly see the goal is to have an interface that has can have
different data (e.g. c1, r1, t1), where you can then use that interface
as a argument in a function and do something (e.g. area(), perimeter()).
TWO INTERFACES VS ONE INTERFACE
The first example shapes-using-interfaces1.go
uses 2 interfaces,
type areaer interface {
area() float64
}
type perimeterer interface {
perimeter() float64
}
The second shapes-using-interfaces2.go
uses more traditional 1 interface,
type shapes interface {
area() float64
perimeter() float64
The end result is the same.
RUN
go run shapes-using-interfaces1.go
go run shapes-using-interfaces2.go