Golang: Polymorphism

Polymorphism is a bit different in Go. It supports polymorphism only through interfaces (and not through inheritance). To help you understand better, here is an example:

import "fmt"

type Car interface {
    func Drive()
}

type Lamborgini struct {
    // Implement the Car interface
    func Drive() {
        fmt.Println("Driving")
    }
}

func driveACar(car Car) {
    car.Drive()
}

// This will work 
lambo := new(Lamborgini)
lambo.Drive() // Will work 
driveACar(lambo)  // Will print "Driving"

However, Polymorphism doesn’t work when driveACar(lammborgini) would not work if Car was a struct and not an interface. Here is an example:

import "fmt"

type Car struct {
    func Drive() {
        fmt.Println("Driving")
    }
}

type Lamborgini struct {
    Car
}

func driveACar(car Car) {
    car.Drive()
}

lambo := new(Lamborgini)
lambo.Drive() // Will call car's Drive method and will work
driveACar(lambo)  // Will throw an error

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *