Provide Best Programming Tutorials

How Golang implements inheritance

Let’s say we have an Animal struct as the base struct, which means it is the ancestor of all animal species.

And it has attributes such as name and age since these attributes are the ones all animals have.

type Animal struct {   
    name string   
    age     int

And we have Dog struct which represents the dog, dog can inherit Animal because the dog is an animal, in Golang we achieve inheritance like this below:

type Dog struct {   

That’s it! Fairly simple! The instance of Dog can have the attributes name and age, no need to define them repeatedly! And you can use the Dog like this below:

func main()  {   
    var Dog dog = "cute dog"   
    dog.age = 5

Leave a Reply

Close Menu