How to achieve composition using embedding in Go?

In Go, achieving composition using embedding is straightforward. Here's how you can achieve it:

  1. Create a struct that represents the base type or component that you want to compose with other types.
type Base struct { // fields and behavior of the base type }
  1. Create other structs that represent the types you want to compose with the base type. Embed the base type in these structs using anonymous field notation.
type Component1 struct { Base // fields and behavior specific to Component1 } type Component2 struct { Base // fields and behavior specific to Component2 }
  1. Define methods for the base type and other components.
func (b *Base) Method1() { // behavior for Method1 of the base type } func (c1 *Component1) Method2() { // behavior for Method2 of Component1 } func (c2 *Component2) Method3() { // behavior for Method3 of Component2 }
  1. Now, you can embed these components in other structs to achieve deeper composition.
type Composed struct { Component1 Component2 // fields and behavior specific to Composed }
  1. Use the composed struct and access methods from the base type and all the embedded components.
c := Composed{} c.Method1() // Access Method1 from the base type c.Method2() // Access Method2 from Component1 c.Method3() // Access Method3 from Component2

Composition using embedding provides the ability to reuse and combine behavior from multiple types, allowing you to create reusable and modular code in Go.