Golang Basics - Interfaces

Interfaces is how Go allows for polymorphism: A common method signature with different implementations.

Defining interfaces

An interface is defined by specifying a method signature:

// We can define an interface by specifying the methods that need to be implemented
type Repairable interface {
        Repair()
}

So now that we have a Repairable interface... how do we implement it?

Implementing interfaces

In most other languages, we need to specify the interface that a class is implementing. Go makes this process easy for you: if a type contains the method signatures of an interface, it implements the interface. Let's look at an example to understand this better. First, we define a Vehicle and Plane struct, which both have a Repair method defined on their pointers:

type Vehicle struct{
        Model string
        Wheels int
}

// The vehicle has a `Repair` method
func (v *Vehicle) Repair(){
       // some vehicle repair code
       fmt.Println("the vehicle is repaired")
}

// We create a new `Plane` struct type
type Plane struct {
        Model string
        Engines int
}

// The plane also has a repair method
func (v *Plane) Repair(){
       // some plane repair code
       fmt.Println("the plane is repaired")
}

car := &Vehicle{
        Model: "BMW",
        Wheels: 4,
}

jet := &Plane{
        Model: "Airbus",
        Engines: 2,
}

We can now define a Repairable type variable and assign the car and jet variables to it:

// We define a new veriable of type `Repairable`
var fixerUpper Repairable

// Since both `car` and `jet` have the `Repair` method
// they both implicitly implement `Repairable`, and so
// they can both be assigned to the fixerUpper variable
fixerUpper = car
fixerUpper = jet

// We can also call the `Repair` method of `fixerUpper`
fixerUpper.Repair()

In the above example, we don't care about the underlying type of fixerUpper. All we know is that we can call it's Repair method.


Liked this article? Share it on: