Inheritance in Golang

Object-oriented programming is a paradigm that works with objects and has 3 properties – Inheritance, Encapsulation, and Polymorphism. Go also supports OOP, but it’s not like other object-oriented languages. It doesn’t support classes. This post will show how go achieves inheritance without classes.

What is inheritance?

In OO-languages inheritance refers to the property that a class can have properties of a superclass and thus inherits it is called inheritance. An example would be a bird class that will be the superclass, whereas the duck class will be the subclass inheriting superclass in that sense that a duck is a bird. This is inheritance in action.

How Go achieves inheritance?

In Go to achieve inheritance structs are used such that the anonymous field property can be used to extend a struct to another struct. This is the simplest way inheritance can be done in Go.

Inheritance using struct

In Go, one can use structs for inheritance. Structs are the building blocks of data structure in Go. The inheritance can be done using struct in a pretty straightforward way. To do inheritance we cannot directly extend, unlike other languages. However, we can compose using structs to form other objects.

Here is an example of how we can compose it.

package main

import "fmt"

type Polygon struct {
	Sides int
}

func (p *Polygon) NSides() int {
	return p.Sides
}

type Triangle struct {
	Polygon // anonymous field
}

func main() {
	t := Triangle{
		Polygon{
			Sides: 3,
		},
	}
	fmt.Println(t.NSides()) // 3
}

The program above uses the anonymous struct field property to reduce unnecessary function calls.

The uses of inheritance

Inheritance allows for subclassing in object-oriented languages. Go doesn’t have that. Instead, it allows for struct embedding to do it. And it is the only way inheritance can be done. Although the composition is preferred in many cases, inheritance is still an important concept. Go, despite not having any real object orientation like the others can still do it to a greater extent.