Skip to content

Zig Defer

Zig has no garbage collector and no destructors. When you borrow memory, open a file or take a lock, it’s your job to give it back. That’s easy to forget, especially when a function has several ways out. defer fixes this: you write the cleanup right next to the setup, and Zig runs it for you when the block ends, however it ends. You’ll see defer in almost every real Zig program, so it’s worth getting comfortable with now.

defer takes a statement and saves it for later. It runs when the program leaves the block the defer is in:

const std = @import("std");
pub fn main() void {
std.debug.print("1. open the shop\n", .{});
defer std.debug.print("4. lock the door\n", .{});
std.debug.print("2. serve customers\n", .{});
std.debug.print("3. count the money\n", .{});
}

Output:

1. open the shop
2. serve customers
3. count the money
4. lock the door

The defer line comes second in the code, but its message prints last, when main ends. You decide what has to happen at the end at the same moment you start something, and then you can stop thinking about it.

Here’s the pattern you’ll write most. Don’t worry about init, !void or try yet; they come in Zig Main & Init and Zig Try & Catch. The important part is the two lines in the middle:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const buffer = try gpa.alloc(u8, 5);
defer gpa.free(buffer);
@memset(buffer, '*');
std.debug.print("buffer: {s}\n", .{buffer});
}

Output:

buffer: *****

gpa.alloc(u8, 5) borrows room for 5 bytes from an allocator (the thing that hands out memory; see Zig Allocators). The very next line, defer gpa.free(buffer);, promises to give it back when main ends. Then @memset fills the bytes with * and we print them.

Leave out the defer line, and the allocator you get from init.gpa notices the leak when the program ends. You’ll see something like:

buffer: *****
error(SafeAllocator): leaked [addr: 7f3e4f2998d0, len: 5 (0x5) align: 1] allocated at:
main.zig:6:33: 0x11e41ea in main (main.zig)
const buffer = try gpa.alloc(u8, 5);
^

The address and the lines below it change from run to run, but the message tells you how many bytes leaked (len: 5) and points right at the allocation you forgot to free.

If a block has several defers, they run last one first. Think of a stack of plates: the last one you put on top is the first one you take off:

const std = @import("std");
pub fn main() void {
std.debug.print("open the database\n", .{});
defer std.debug.print("close the database\n", .{});
std.debug.print("open the log file\n", .{});
defer std.debug.print("close the log file\n", .{});
std.debug.print("do the work\n", .{});
}

Output:

open the database
open the log file
do the work
close the log file
close the database

This order is exactly what you want. Things are usually set up in layers: the log file was opened after the database, and might still need it, so it should be closed first. Reverse order undoes the layers from the top down.

defer belongs to the block, not the function

Section titled “defer belongs to the block, not the function”

A defer runs at the end of the block it’s written in, not at the end of the function. In a loop body, that means it runs at the end of every round:

const std = @import("std");
pub fn main() void {
for (1..4) |round| {
defer std.debug.print(" end of round {d}\n", .{round});
std.debug.print("start of round {d}\n", .{round});
}
{
defer std.debug.print("inner block done\n", .{});
std.debug.print("inside the inner block\n", .{});
}
std.debug.print("end of main\n", .{});
}

Output:

start of round 1
end of round 1
start of round 2
end of round 2
start of round 3
end of round 3
inside the inner block
inner block done
end of main

The real value of defer shows when a block has more than one exit: an early return, a break, a continue. The deferred code runs on all of them:

const std = @import("std");
fn checkAge(age: u8) void {
std.debug.print("checking {d}\n", .{age});
defer std.debug.print(" done with {d}\n", .{age});
if (age < 13) {
std.debug.print(" too young\n", .{});
return;
}
if (age > 120) {
std.debug.print(" that can't be right\n", .{});
return;
}
std.debug.print(" welcome!\n", .{});
}
pub fn main() void {
checkAge(9);
checkAge(30);
}

Output:

checking 9
too young
done with 9
checking 30
welcome!
done with 30

checkAge is a small function with three ways to finish, and the “done” line prints for every one. Without defer, you’d have to copy the cleanup in front of each return, and the day someone adds a fourth return they’ll forget it.

Two details trip people up.

The values are read when the defer runs, not when you write it. A defer doesn’t take a snapshot. It runs the statement later, with whatever the variables hold at that point:

const std = @import("std");
pub fn main() void {
var count: u32 = 1;
defer std.debug.print("count at the end: {d}\n", .{count});
count = 10;
std.debug.print("count now: {d}\n", .{count});
}

Output:

count now: 10
count at the end: 10

A return value is worked out before the defers run. So a defer can’t sneak in and change what a function returns:

const std = @import("std");
fn getValue() u32 {
var x: u32 = 1;
defer x = 99;
return x;
}
pub fn main() void {
std.debug.print("returned {d}\n", .{getValue()});
}

Output:

returned 1

return x decides on 1 first, then the defer sets x to 99, which no longer matters.

Also, a defer only counts if the program actually reaches that line. A defer inside an if that didn’t run, or after an early return, never gets scheduled.

A defer is for cleanup, so it can’t jump out of the block. A return inside one is an error:

fn getValue() u32 {
defer {
return 5;
}
return 1;
}
pub fn main() void {
_ = getValue();
}
main.zig:3:9: error: cannot return from defer expression
return 5;
^~~~~~~~
main.zig:2:5: note: defer expression here
defer {
^~~~~

As the example shows, defer { ... } with braces lets you defer several statements at once. _ = getValue(); throws the result away; Zig makes you say so when you ignore a value.

Sometimes cleanup should happen only if something goes wrong. For example, a function that builds something and hands it to the caller should free it if it fails halfway, but keep it if it succeeds. That’s errdefer: it runs only when the block is left with an error:

const std = @import("std");
fn connect(fail: bool) !void {
std.debug.print("open connection\n", .{});
errdefer std.debug.print("close connection (something failed)\n", .{});
defer std.debug.print("connect() finished\n", .{});
if (fail) return error.Timeout;
std.debug.print("connected!\n", .{});
}
pub fn main() void {
connect(false) catch {};
std.debug.print("---\n", .{});
connect(true) catch |err| std.debug.print("error: {s}\n", .{@errorName(err)});
}

Output:

open connection
connected!
connect() finished
---
open connection
connect() finished
close connection (something failed)
error: Timeout

The first call succeeds, so only the defer runs. The second returns error.Timeout, so both run, last one first as usual. !void, return error.Timeout and catch are how Zig does errors; you’ll learn them in Zig Errors, and errdefer gets its own lesson in Zig Errdefer. The language reference on defer has the short official version.

Before running it, write down what this prints. Then run it and check.

const std = @import("std");
pub fn main() void {
defer std.debug.print("A\n", .{});
{
defer std.debug.print("B\n", .{});
std.debug.print("C\n", .{});
}
defer std.debug.print("D\n", .{});
std.debug.print("E\n", .{});
}

Hint: the inner block ends before D is even scheduled. At the end of main, the defers left run newest first.

Show solution

Output:

C
B
E
D
A

C prints, then the inner block ends and runs B. Then E prints. When main ends, its two defers run in reverse: D (the newest), then A.

Write a program that prints a top line +------+, then the word Zig, then a bottom line +------+. Use defer for the bottom line, written right after the top line.

Hint: print the top, then defer the bottom, then print the middle.

Show solution
const std = @import("std");
pub fn main() void {
std.debug.print("+------+\n", .{});
defer std.debug.print("+------+\n", .{});
std.debug.print(" Zig\n", .{});
}

Output:

+------+
Zig
+------+

The opening and closing lines sit together in the code, even though they print at different times. That’s the same shape as allocate and free.

This loop should count every round, but it skips the rounds that hit continue, so it prints rounds: 2 instead of rounds: 4. Fix it with defer, without removing the continue.

const std = @import("std");
pub fn main() void {
const values = [_]i32{ 5, -1, 8, -2 };
var rounds: u32 = 0;
for (values) |v| {
if (v < 0) continue;
std.debug.print("value {d}\n", .{v});
rounds += 1;
}
std.debug.print("rounds: {d}\n", .{rounds});
}

Hint: a defer at the top of the loop body runs at the end of every round, even after continue.

Show solution
const std = @import("std");
pub fn main() void {
const values = [_]i32{ 5, -1, 8, -2 };
var rounds: u32 = 0;
for (values) |v| {
defer rounds += 1;
if (v < 0) continue;
std.debug.print("value {d}\n", .{v});
}
std.debug.print("rounds: {d}\n", .{rounds});
}

Output:

value 5
value 8
rounds: 4

continue leaves the loop body early, and leaving the body is exactly when a defer in it runs.

  • defer statement; runs the statement when the current block ends.
  • Put cleanup right after setup: alloc then defer free, open then defer close.
  • Several defers run in reverse order, last one first.
  • defer belongs to the block, not the function: in a loop, it runs every round.
  • It runs on every way out: the end of the block, return, break and continue.
  • Variables are read when the defer runs, and a return value is fixed before defers run.
  • errdefer runs only when the block is left with an error.

Next up: Zig Unreachable, for telling Zig “this can never happen”, and what happens when it does.

Quick check

1. A function has defer print("1") and then defer print("2"). What prints when it ends?
2. You put a defer inside the body of a for loop that runs 3 times. How often does it run?
3. With var x: u32 = 1; defer print(x); x = 10;, what does the defer print?
4. When does errdefer run?