Chapter 11The Price of AbstractionPaid chapter

Closures and defer: Capture, Escape, and Compiler Transforms

Distinguish closure records, shared mutable cells, and defer execution paths.

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

Closures are slow because they allocate, and defer has constant overhead you should avoid in hot code.

What actually happens

the supplied local closure is inlined and allocates nothing; a returned closure can allocate a record containing copied captures or pointers to shared cells. And defer has three cost regimes, not one: up to 8 straight-line defers are open-coded (inlined, effectively free); more than 8, or anything too complex, falls back to runtime-managed defers (~an order of magnitude slower per defer, no heap garbage); and a defer in a loop pays that runtime cost every iteration, with the deferred calls accumulating until the function returns. On current Go, none of these produce steady-state heap allocations — the _defer records are pooled — so the cost is time and accumulation, not garbage. The keyword's cost depends entirely on the shape of its use.

Mechanisms covered
Open-coded, stack-record, and dynamically registered defers have different implementation paths.
Warm record reuse does not guarantee zero allocations for arbitrary deferred arguments or cold workloads; cleanup waits until return.
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
Distinguish escape diagnostics from measured allocations and explain the role of lifetime and call-site visibility.
Free chapter
Maps: Swiss Tables, Growth, and Permanent Memory
Distinguish map table capacity from referenced payloads and inspect clearing and growth on Go 1.25.