Golang Inheritance Guide: Struct Embedding Explained
In Go language, there is no inheritance mechanism like in other object-oriented languages, but similar functionality can be achieved through struct embedding and interfaces.
Nested struct can achieve functionality similar to inheritance. A child struct can contain the fields of a parent struct, thus achieving field inheritance. For example:
type Animal struct {
Name string
}
type Dog struct {
Animal
Breed string
}
func main() {
dog := Dog{
Animal: Animal{
Name: "Buddy",
},
Breed: "Labrador",
}
fmt.Println(dog.Name) // Output: Buddy
}
Another way to achieve similar functionality to inheritance is to use interfaces. If a struct implements a certain interface, it can then call the methods defined in that interface. For example:
type Animal interface {
GetName() string
}
type Dog struct {
Name string
}
func (d Dog) GetName() string {
return d.Name
}
func main() {
var animal Animal
dog := Dog{
Name: "Buddy",
}
animal = dog
fmt.Println(animal.GetName()) // Output: Buddy
}
Although Go language does not provide a traditional inheritance mechanism, similar functionality can be achieved through struct embedding and interfaces.