In Go, achieving composition using embedding is straightforward. Here's how you can achieve it:
type Base struct {
// fields and behavior of the base type
}
type Component1 struct {
Base
// fields and behavior specific to Component1
}
type Component2 struct {
Base
// fields and behavior specific to Component2
}
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
}
type Composed struct {
Component1
Component2
// fields and behavior specific to Composed
}
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.