Closures and defer: Capture, Escape, and Compiler Transforms
Distinguish closure records, shared mutable cells, and defer execution paths.
This chapter is part of the paid launch. The preview stays visible so readers can evaluate the exact scope before buying.
Core and Complete. Complete also includes the practical exam and free Go-version updates.
What this chapter teaches
Closures are slow because they allocate, and defer has constant overhead you should avoid in hot code.
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.
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.
Full course access with the complete mechanics curriculum.
Best-value launch option with the exam and free Go-version course updates.
No subscription or account required. Access is tied to the email entered at Stripe Checkout and can be restored by email.