typestar

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

  1. Each defer is registered when the line is reached, not when it runs.
  2. At scope exit they fire last-declared first: pour the cup, then kettle off.
  3. The pattern keeps acquisition and release adjacent in the source.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Errors, step 9 of 27 in Language basics.

← Previous Next →

defer in other languages