May 24, 2020 | 12:49

Inheritance with Golang

I took dozen of Golang interviews over past 6 months. In all of them, I asked people to solve a very simple problem. The problem is: there are 3 entities Student, Teacher and Employee. All these 3 entities will have a name parameter. I need a method which will print name of that entity on console. There must be only one implementation of the method and I should be able to call the method as below

    var s Student
    s.PrintName()

    var t Teacher
    t.PrintName()

Sounds simple, right? Surprisingly, only 2-3 candidates gave the expected answer, others chose interfaces to solve this. They would define printName() as interface method and then I would go on to ask them would it not require 3 methods each for one entity? That would confuse them and they would then come up with even bizzare solution to this problem using interfaces.

The solution

This problem does not require interfaces at all. Consider below code

    type People struct{
        Name struct
    }

    func (p *People) PrintName(){
        fmt.Println("Name:", p.Name)
    }

    type Student struct{
        People
    }

    type Teacher struct{
        People
    }

Below code now works perfectly

    var s Student
    s.PrintName()

    var t Teacher
    t.PrintName()

The name parameter is common across all three entities so we define new entity called Person and embed it inside all three entities. We implement a method call PrintName() on Person struct and that method becomes available for all three entities.

As you can see, embedding is the fastest way to acheieve inheritance in Golang. That’s all for now people.

Take care & have a great day!

© Ankshilp 2020

Powered by Hugo & Kiss'Em.