How to use embedding to implement composition over inheritance in Go?

Using embedding in Go allows you to implement composition over inheritance. Here's how you can do it:

  1. Create a struct representing the base/parent class with the common fields and methods.
type Animal struct { name string } func (a *Animal) Eat() { fmt.Println(a.name, "is eating.") }
  1. Create structs representing the derived/child classes by embedding the base class.
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.") }
  1. You can now use the derived classes and access the common fields and methods through the embedded base class.
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.