Inheritance in Golang
Oct 30, 2020
Basically, Golang is not an OOP language so there is no inheritance concept in Golang. However, structs still can be extended through struct embedding. But keep in mind that if you redefine a property in your sub struct, struct embedding will not inherit the property from the embedded struct any more.
Now let’s take a look on the following example of struct embedding.
package mainimport (
"fmt"
)type Animal struct {
Age int
Leg int
}func (a *Animal) Move() {
fmt.Println("An animal moves by ", a.Leg, " legs.")
}type Dog struct {
Animal
Leg int
}func (d *Dog) Move() {
fmt.Println("A dog moves by ", d.Leg, " legs.")
}func main() {
animal := Animal{
Age: 5,
Leg: 2,
}
// Output: "An animal moves by 2 legs."
animal.Move()
dog := Dog{
Animal: Animal{Age: 5, Leg: 4},
}
// Here if you expect an output of "A dog moves by 4 legs." then you never get it.
// Instead you will get "A dog moves by 0 legs."
dog.Move()
}
In you are interested in this example, you can test it on Golang playground at https://play.golang.org/p/xUYw53rMTXj