Interfaces in Golang

·

2 min read

Introduction

Interfaces in go is just another type like int, strings, float. It contains method signatures. Simply speaking interface contains a bunch of methods very similar to java, if you've ever come across the interface topic in java. for e.g.


type geometry interface {
    area() float64
    perim() float64
}

For beginners to understand the code more clearly :

Geometry : an Interface type

area() float64 : a method returning a type float64

perim() float64 : a method returning a type float64

It if for the programmer to define/Implement what these methods do inside his program.

NOTE: all the methods should be Implemented that are present in a Interface. Only then we can say we've implemented the Interface.

Implementing the methods.

We can implement methods only using the types that are declared inside the programs, this means built-in types can't be used too. Usually we have to create our own types e.g.

type mytype1 int

type mytype2 struct { sentence string }

a typical implementation of a method looks like this

func (inp1 mytype1) area() float64 { // random implementation }

func (inp1 mytype1) perim() float64 { // random implementation }

Well since both of the methods are implemented , we can say we've Implemented the geometry Interface successfully. Note that the return types should be same as defined inside the interface and mytype1 is a type defined inside the program. In case you're wondering syntax looks a bit weird, yeah it does cause these are methods and the inputs arguments are stated first in methods but these methods can also be written like :

func area( inp1 mytype1) float64 { // random implementation }

func perim( inp1 mytype1 ) float64 { // random implementation }

In the first representation of method Implementation inp1 are called Receiver argument and that's usually how methods look like in Golang.

In Golang we use a bit of different analogy when defining the methods, for the above examples we can say the mytype1 implements the area and perim methods. if mytype1 would have been a pointer ( *mytype1 ) then the mytype1 pointer type would've implemented both of these methods. Hence, it would only take a pointer variable of mytype1 as input. Since we are not using the implement keyword in here which is not the case with other languages. Therefore we can say that Interfaces are implemented implicitly in Golang.