Categories
Uncategorized

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

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

Leave a Reply

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