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, Complete, and Team. 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 closures that escape (which heap-allocate their captures).

Mechanisms covered
Launching a closure as a goroutine forces all captures to escape (goroutine lifetime is unknowable).
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
Early accessUnlock Chapter 11

Unlock Chapter 11 and the rest of the course.

Choose a plan and request access. Core unlocks the paid chapters, Complete adds the exam and free Go-version updates, and Team gives you 5 seats.

Choose a plan

Submit your email and selected plan to request launch access. No subscription. Complete also includes the practical exam and free Go-version updates.

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.