Using embedding in Go allows you to implement composition over inheritance. Here's how you can do it:
type Animal struct {
name string
}
func (a *Animal) Eat() {
fmt.Println(a.name, "is eating.")
}
type Dog struct {
*Animal
breed string
}
func NewDog(name, breed string) *Dog {
return &Dog{
Animal: &Animal{name: name},
breed: breed,
}
}
func (d *Dog) Bark() {
fmt.Println(d.name, "is barking.")
}
type Cat struct {
*Animal
color string
}
func NewCat(name, color string) *Cat {
return &Cat{
Animal: &Animal{name: name},
color: color,
}
}
func (c *Cat) Meow() {
fmt.Println(c.name, "is meowing.")
}
func main() {
dog := NewDog("Max", "Labrador")
dog.Eat() // Accessing the Eat method of the Animal base class
dog.Bark() // Accessing the Bark method of the Dog class
cat := NewCat("Whiskers", "Black")
cat.Eat() // Accessing the Eat method of the Animal base class
cat.Meow() // Accessing the Meow method of the Cat class
}
In this example, the Dog
and Cat
structs embed the Animal
struct, which allows them to inherit its behavior and access its fields and methods. This achieves composition over inheritance as the derived classes are composed of the base class instead of inheriting from it.