liveBook · Manning

Defer

As explained in Systems Programming with Zig

In Zig, defer schedules an expression or block to execute when the enclosing scope exits.

In Zig, defer schedules an expression or block to run when its enclosing scope exits—on return, error propagation with try, or the end of a block. section 3.4.2

Use defer to keep cleanup reliable and close to the resource it protects:

  • Free allocated memory with defer so it is released even if a later operation fails. section 3.4.2
  • Use errdefer for cleanup that should run only when an error is returned; defer and errdefer can both take a block. section 3.4.2
for (args[1..]) |filepath| {
    const text = try cwd.readFileAlloc(
        init.gpa,
        filepath,
        io,
        .unlimited,
    );
    defer init.gpa.free(text);

    try stdout.writeAll(text);
}

In this cat loop, each file buffer is freed when the loop body’s scope exits, including if writing to stdout fails. section 3.4.2

How Systems Programming with Zig covers it

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.
How it connects
Connects to allocators, memory management, error propagation, and errdefer.

Also explained in

Compare how 4 books explain defer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.