Skip to content

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?

  1. Avoid Fragility: Deep inheritance trees are easy to break. If you change the “Grandparent” class, you might break 50 “Child” classes.
  2. Clearer Logic: It’s always obvious where a field or method came from.
  3. Flexibility: You can easily swap an Engine struct for an ElectricMotor struct.

🥅 Module 2 Review

  1. Embedding: Putting one struct inside another to share fields and methods.
  2. Composition: Building complex behavior from simple parts.
  3. 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.