shapes-using-interfaces

command
v0.0.0-...-a2a1f02 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2020 License: MIT Imports: 2 Imported by: 0

README

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

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL