Defer
Defer is a language feature that schedules code to execute when its enclosing scope or function exits.
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.
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 defer to keep resource cleanup and status reporting near their setup without repeating calls at every return.
- How deep it goes
- Explains function boundaries, immediate argument and receiver evaluation, and deferred error handling through contrasting implementations.
- Examples
- Uses file iteration, status notification, database row closure, and HTTP response bodies to expose deferred-call mistakes.
- What you can do after
- Diagnoses delayed cleanup, stale arguments, receiver surprises, and ignored close errors, then selects a contextual fix.
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 →
Systems Programming with Zig
In Zig, defer schedules an expression or block to execute when the enclosing scope exits.
- How it is used
- Protects resource cleanup in manual-memory-management code, including paths that exit early or propagate errors.
- How deep it goes
- Defines scope-exit behavior and demonstrates deferred cleanup in a file-printing loop; it does not explore implementation internals.
- Examples
- Uses a cat loop that reads file contents, writes them to stdout, and frees each buffer.
- What you can do after
- Apply defer to release allocated file contents when a scope exits, including when output writing fails.
Also covered in
What to know first
- GoGo is a statically typed, compiled, general-purpose programming language with garbage collection and built-in support for concurrency.
- JSONJSON is a language-independent text-based data-interchange format that represents structured values using objects, arrays, strings, numbers, booleans, and null.
- panicA panic is a runtime failure state or mechanism that interrupts ordinary execution when a failure or violated assumption prevents safe continuation, potentially triggering recovery, stack unwinding, or termination.
- TCPTCP (Transmission Control Protocol) is a connection-oriented transport-layer protocol that provides reliable, ordered delivery of a byte stream between network endpoints.
Related concepts
- closeuses · Close is an operation that ends active use of an associated resource or interface and may release or finalize related resources or pending work.
- close functionuses · In Go, close is a built-in function that marks a channel closed, preventing further sends and allowing receivers to detect completion.
- resource cleanupaddresses · Resource cleanup is the release of resources or restoration of state when an operation or scope ends or fails.
- functionuses · A function is a callable unit of program code that performs a computation or operation, can accept inputs, and may produce a result or side effect.
Questions about defer
What is defer?
Defer is a language feature that schedules code to execute when its enclosing scope or function exits.
Which Manning books explain defer?
Go in Practice, Second Edition, 100 Go Mistakes and How to Avoid Them, Learn Go with Pocket-Sized Projects and Systems Programming with Zig.
What should I know before learning defer?
Manning books that teach defer usually introduce Go, JSON, panic and TCP first.
What is the difference between defer and os.Exit?
Defer is a language feature that schedules code to execute when its enclosing scope or function exits. os.Exit is a Go standard-library function that immediately terminates the calling process with a specified exit status code.
What kinds of defer are there?
Kinds of defer include errdefer.
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.



