defer

defer

defer.zig

const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;

// defer will execute an expression at the end of the current scope.
fn deferExample() usize {
    var a: usize = 1;

    {
        defer a = 2;
        a = 1;
    }
    assert(a == 2);

    a = 5;
    return a;
}

test "defer basics" {
    assert(deferExample() == 5);
}

// If multiple defer statements are specified, they will be executed in
// the reverse order they were run.
fn deferUnwindExample() void {
    warn("\n", .{});

    defer {
        warn("1 ", .{});
    }
    defer {
        warn("2 ", .{});
    }
    if (false) {
        // defers are not run if they are never executed.
        defer {
            warn("3 ", .{});
        }
    }
}

test "defer unwinding" {
    deferUnwindExample();
}

// The errdefer keyword is similar to defer, but will only execute if the
// scope returns with an error.
//
// This is especially useful in allowing a function to clean up properly
// on error, and replaces goto error handling tactics as seen in c.
fn deferErrorExample(is_error: bool) !void {
    warn("\nstart of function\n", .{});

    // This will always be executed on exit
    defer {
        warn("end of function\n", .{});
    }

    errdefer {
        warn("encountered an error!\n", .{});
    }

    if (is_error) {
        return error.DeferError;
    }
}

test "errdefer unwinding" {
    deferErrorExample(false) catch {};
    deferErrorExample(true) catch {};
}
``` ```
$ zig test defer.zig
1/3 test "defer basics"...OK
2/3 test "defer unwinding"...
2 1 OK
3/3 test "errdefer unwinding"...
start of function
end of function

start of function
encountered an error!
end of function
OK
All 3 tests passed.

See also:

  • Errors