logo

Lucas Katayama/Interfaces

Created Tue, 17 Dec 2019 16:46:45 -0300 Modified Tue, 17 Dec 2019 16:46:45 -0300
230 Words

This is one of the most interesting things about Go: Interfaces.

Intro

If quacks like a duck. Then it is a duck.

This features really bothered me in Java. Every class that I need to implement an interface, I need to declare which interface that I am going to implement.

In Go, this is different. If a struct has a method implementing an interface, than it is already done.

Structs

Lets create some structures:

type Square struct {
    X float64
}

type Rectangle struct {
    X, Y float64
}

Interface

Now we want to calculate the area and print it. So each one need to have an interface called Area():

type IArea interface {
    Area() float64
}

And then we implement it:

func (s Square) Area() float64 {
    return s.X * s.X
}

func (r Rectangle) Area() float64 {
    return r.X * r.Y
}

Using it

So, to use each one to print:

func PrintArea(area IArea) {
    fmt.Println(area.Area())
}

func main() {
    square := Square{X: 2.0}
    rectangle := Rectangle{X: 2.0, Y: 4.0}

    PrintArea(square)
    PrintArea(rectangle)
}

If you try to use some structure without implementing the interface, the compiler gives an error:

type Triangle struct {
    height, base float64
}

func main() {
    square := Triangle{height: 2.0, base: 3.0}

    PrintArea(triangle)
}
cannot use rectangle (type Triangle) as type IArea in argument to PrintArea:
	Triangle does not implement IArea (missing Area method)