Type Embedding
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.
We can define couple methods on the engine.
Now let's build a car with this turbo charged engine by embedding it into a car struct.
Output:
Notice that ignite
is also embedded onto Car
. I made it private so that starting an engine is abstracted away from user.
Interface Embedding
Now you may ask, what if I want a different engine like a naturally aspirated 6 cylinder? You can achieve it by embedding interfaces.
Change the embedded type to Engine
Now we can put whatever engine we like into our car.
Last updated