Module 2: Composition (The Lego Blocks)
📚 Module 2: Composition
Course ID: GO-113
Subject: The Lego Blocks
Go developers follow the rule: “Composition over Inheritance.” We don’t build deep family trees. We build complex things by putting smaller pieces together.
🏗️ Step 1: Embedding
Instead of a “Child” inheriting from a “Parent,” we Embed one struct inside another.
🧩 The Analogy: The Lego Castle
- You don’t “inherit” a Wall from a Brick.
- You build a Wall by putting Bricks inside it.
In Go:
type Engine struct {
Horsepower int
}
type Car struct {
Engine // This is EMBEDDING. Car now has Horsepower!
Model string
}
func main() {
c := Car{
Engine: Engine{Horsepower: 300},
Model: "Mustang",
}
fmt.Println(c.Horsepower) // You can access it directly!
}🏗️ Step 2: Why do we do this?
- Avoid Fragility: Deep inheritance trees are easy to break. If you change the “Grandparent” class, you might break 50 “Child” classes.
- Clearer Logic: It’s always obvious where a field or method came from.
- Flexibility: You can easily swap an
Enginestruct for anElectricMotorstruct.
🥅 Module 2 Review
- Embedding: Putting one struct inside another to share fields and methods.
- Composition: Building complex behavior from simple parts.
- No Classes: Go uses this pattern instead of traditional OOP classes.
:::tip Senior Tip Go’s embedding is so powerful that if you embed a struct that follows an interface, the outer struct now follows that interface too! ::: Riverside. Riverside.