In order to achieve composition, we need to take a look at type embedding in Go. Suppose we are trying to build a car. A car is composed of many small moving parts. We want to be able to reuse these small moving parts to build different type of cars.
Struct Embedding
First we have a turbo charged four cylinder engine.
type Engine interface {
ignite()
}
type NatAspirated struct {
Horsepower int
Torque int
}
func (na NatAspirated) ignite() {
fmt.Printf("6 cylinder is running, VROOOOMMMMM\n")
}
type Car struct {
Engine
}
func (c Car) Start() {
c.ignite()
}
func main() {
var c Car
c = Car{NatAspirated{400, 450}}
// OR
c = Car{TurboCharged{300, 305, 2, 100.5}}
c.Start()
}