liveBook · Manning

Defer

As explained in Learn Go with Pocket-Sized Projects

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

defer schedules a statement to run when the surrounding function returns. It keeps cleanup beside the operation that requires it, so refactoring or early returns do not easily skip resource release. section 3.1.2 section 3.5

Close an opened file

f, err := os.Open(filePath) if err != nil { return nil, err } defer f.Close() The file closes when the function returns, regardless of which return path it takes. section 3.1.2

How Learn Go with Pocket-Sized Projects covers it

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 it assumes
Assumes functions, return paths, and file opening while reinforcing explicit resource cleanup after os.Open or os.Create.
What you can do after
Apply defer to schedule cleanup reliably when writing Go functions that open files.
How it connects
Connects function returns with file I/O, resource cleanup, and buffered I/O practices.

Also explained in

Compare how 3 books explain defer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.