Inheritance in Go

Amit Jain
The Startup
Published in
2 min readSep 4, 2020
Inheritance

Go doesn’t have a concept of class or have a class-based inheritance. Go is a bit different than the regular object-oriented languages.

How we can reuse the code if Inheritance is not there?

Go has a unique feature called embedded fields in the struct(More like composition). Using those we can reuse the code, it is pretty much similar to what Inheritance provides in other languages.

The Embedded field is a special field, a field without a field name. Let’s have a look at the below example :

As mentioned in the above example: Animal is an embedded field in the parrot struct. The Animal struct is behaving like a base struct and Parrot struct has inherited all the fields and methods of it.
Let’s have a look at our main function:
line 30: We are calling a method Eat which is overridden by parrot struct.
line 33: We are calling a method Sleep which is a method of the animal struct(The parent struct).
line 35: We are using field(Weight) of the Animal as it is of Parrot field.

So we understood how we can reuse the code(Use inheritance features) in Go.

But Is there a benefit of using embedded fields?
Yes, the similar benefits we get with the below design principles:

Favor composition over inheritance

Many times we require our code to be more flexible and change its behavior at the run time. Inheritance is a very tightly coupled feature, as it is defined at compile time we can’t change the class behavior at run time. With composition, we can always change the class behavior with dependency injection or setters.

As in the above example, we could have embedded an interface in the Parrot struct(Yes, the Embedded feature is available for both struct and interface. We could have an animal interface embedded in the parrot struct).

type Animal interface {
Eat()
Sleep()
}

Then we can change the Parrot behavior at runtime by setting the Animal field with any struct satisfying the Animal Interface. For example:

If you have reached here, you might like my other blog on Design patterns in Golang.

--

--