Polymorphism in GoLang

In Object-Oriented Programming, an object can behave like another object. This property is called polymorphism. This post will cover how we achieve polymorphism in GoLang.

What is polymorphism?

Polymorphism is a property that is available to many OO-languages. Go despite not being an OO-language achieves polymorphism through interfaces.

Polymorphism using interfaces

In GoLang, polymorphism is achieved mainly using interfaces. A type implementing a function defined in interface becomes the type defined as an interface. This is the property that makes polymorphism achievable in Go.

Here is an example of polymorphism in action.

package main

import "fmt"

// declare interface
type Dog interface {
	Bark()
}

// declare struct
type Dalmatian struct {
	DogType string
}

// implement the interface
func (d Dalmatian) Bark() {
	fmt.Println("Dalmatian barking!!")
}

func MakeDogBark(d Dog) {
	d.Bark()
}

func main() {
	d := Dalmatian{"Jack"}
	MakeDogBark(d)                    // Dalmatian barking!!
}

In the code above, the struct Dalmatian implements the Dog interface. Thus the struct becomes the type Dog and so that it can be passed in that function.

Now, we can simply add any type and implement that interface and the type will behave as that interface. That is polymorphism. An object taking many different forms.

Uses of polymorphism

Polymorphism is used to reduce code in general. There will be less coupling if polymorphism is used. A single function can be used to do the same thing on multiple different objects. This is where polymorphism is heavily used. It is one of the most important concepts in OO-Programming. Go not being a strict OO-language achieves polymorphism in an elegant way.