Chapter 11The Price of AbstractionPaid chapter

Closures and defer — Capture, Escape, and Compiler Transforms

Understand closure allocation mechanics, defer's cost model, and when open-coded defer eliminates overhead.

Launch paywall

This chapter is part of the paid launch. The preview stays visible so readers can evaluate the exact scope before buying.

Included in

Core and Complete. Complete also includes the practical exam and free Go-version updates.

Preview

What this chapter teaches

Common belief

defer is slow; avoid it in hot paths" and "closures are just functions.

What actually happens

simple unconditional defers are open-coded and effectively free; the real costs are defers in loops (a runtime call per iteration and cleanup delayed until return — time and accumulation, not heap garbage: records are pooled on current Go) and escaping closure records and any separately shared mutable cells.

Mechanisms covered
A launched closure can retain copied captures or pointers to shared state; inspect escape and capture diagnostics.
Open-coded defer (Go 1.13+) compiles simple, unconditional defers into inline code with a bitmask, eliminating the _defer record. Defers in loops or functions with >8 defers fall back to heap allocation.
benchcompileexperiment
One-time purchase

Unlock Chapter 11 and the rest of the course.

Core unlocks every paid chapter and lab. Complete also includes the practical exam and future Go-version updates.

Core
$49

Full course access with the complete mechanics curriculum.

All paid chapters unlocked
One-time purchase
Perfect if you want the material only
Complete
$79
Best value

Best-value launch option with the exam and free Go-version course updates.

Everything in Core
Black Belt practical exam
Free Go-version updates

No subscription or account required. Access is tied to the email entered at Stripe Checkout and can be restored by email.

Free chapter
Escape Analysis — The Compiler's Fragile Decision
Understand how the compiler decides between stack and heap allocation, why the decision is fragile, and how to verify it.
Free chapter
Maps — Swiss Tables, Growth, and Permanent Memory
Understand the Go 1.24+ Swiss Table map layout, why maps don't shrink, and how to design for memory reclamation.