☰ All patterns
Composite
Treat single items and groups of items the same way.
01
Explain it like I'm new
Real-life analogy
Boxes inside boxes
To weigh a shipment you don't care if something is a single item or a box full of smaller boxes. Ask anything its weight; boxes just add up what's inside.
😩 The problem
A folder contains files and other folders. Code that computes total size ends up full of type checks and special cases.
💡 The pattern
Give leaves (File) and containers (Folder) the same interface. Containers implement methods by delegating to their children, which recurses naturally.
02
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
03
When should I use it?
✅ Reach for it when…
- •Trees: file systems, UI components, org charts, menus, ASTs.
🚫 Skip it when…
- •Your data isn't hierarchical.
🐹 Go tip
Go's go/ast package models source code as a composite tree of ast.Node values.
🌍 You've already seen it in
go/ast nodes, html.Node trees and fs.FS directory walking.
04
Quick check
One question. No pressure.
Why does Folder.Size() not need to check whether a child is a File or a Folder?