liveBook · Manning

Defer

Defer is a language feature that schedules an operation to execute when the surrounding function or scope exits, including during exceptional unwinding.

How 3 Manning books explain it

Go in Practice, Second Edition

A deferred function is a function call scheduled by Go to execute when its surrounding function returns, including during panic unwinding.

How it is used
Schedules cleanup after acquiring HTTP bodies, files, or network connections, and runs panic-recovery handlers during unwinding.
How deep it goes
Explains execution on return or panic, closure scope, recovery mechanics, and the `os.Exit` exception without detailing runtime implementation.
Examples
Uses an HTTP response body, printed execution order, a recovering closure, closure-scope examples, and a network log client.
What you can do after
Practice/perform deferred resource cleanup and panic recovery while avoiding `log.Fatal*` when cleanup must run.

Read how Go in Practice, Second Edition explains defer →

100 Go Mistakes and How to Avoid Them

A defer statement schedules a function call to execute when the surrounding function returns, including during panic unwinding.

How it is used
Uses deferred calls to centralize resource cleanup and status reporting across returns.
How deep it goes
Traces function-return timing and immediate argument evaluation, then works through deferred cleanup errors rather than runtime internals.
Examples
Contrasts file-opening loops with per-file functions, and shows status calls receiving an unexpectedly empty string.
What you can do after
Diagnose/debug with it: prevent loop-bound descriptor leaks and deferred calls that receive stale values.

Read how 100 Go Mistakes and How to Avoid Them explains defer →

Learn Go with Pocket-Sized Projects

defer is a Go language feature that schedules a function call to execute when the surrounding function returns.

How it is used
Uses deferred cleanup to keep file-resource management next to opening operations and protect it across return paths.
How deep it goes
Defines deferred execution, demonstrates return-time ordering, and applies it to file closing without examining runtime internals.
Examples
Demonstrates deferred print statements and defers file.Close immediately after os.Open succeeds.
What you can do after
Apply defer to schedule cleanup reliably when writing Go functions that open files.

Read how Learn Go with Pocket-Sized Projects explains defer →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.