defer in Zig
Cleanup declared next to the thing it cleans: defer runs at scope exit, in reverse.
const std = @import("std");
fn brew() void {
// defer runs at scope exit, last-declared first.
std.debug.print("kettle on\n", .{});
defer std.debug.print("kettle off\n", .{});
defer std.debug.print("pour the cup\n", .{});
std.debug.print("three minutes steeping\n", .{});
}
pub fn main() void {
brew();
std.debug.print("milk first, obviously\n", .{});
}
How it works
- Each
deferis registered when the line is reached, not when it runs. - At scope exit they fire last-declared first: pour the cup, then kettle off.
- The pattern keeps acquisition and release adjacent in the source.
Keywords and builtins used here
constdeferfnpubvoid
The run, in numbers
- Lines
- 14
- Characters to type
- 355
- Tokens
- 112
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 90 seconds.
Step 3 of 3 in Errors, step 9 of 27 in Language basics.