defer
test_defer.zig
const std = @import("std");
const expect = std.testing.expect;
const print = std.debug.print;
// defer will execute an expression at the end of the current scope.
fn deferExample() !usize {
var a: usize = 1;
{
defer a = 2;
a = 1;
}
try expect(a == 2);
a = 5;
return a;
}
test "defer basics" {
try expect((try deferExample()) == 5);
}
// If multiple defer statements are specified, they will be executed in
// the reverse order they were run.
fn deferUnwindExample() void {
print("\n", .{});
defer {
print("1 ", .{});
}
defer {
print("2 ", .{});
}
if (false) {
// defers are not run if they are never executed.
defer {
print("3 ", .{});
}
}
}
test "defer unwinding" {
deferUnwindExample();
}
Shell
$ zig test test_defer.zig
1/2 test.defer basics... OK
2/2 test.defer unwinding...
2 1 OK
All 2 tests passed.
test_invalid_defer.zig
// Inside a defer expression the return statement is not allowed.
fn deferInvalidExample() !void {
defer {
return error.DeferError;
}
return error.DeferError;
}
Shell
$ zig test test_invalid_defer.zig
docgen_tmp/test_invalid_defer.zig:4:9: error: cannot return from defer expression
return error.DeferError;
^~~~~~~~~~~~~~~~~~~~~~~
docgen_tmp/test_invalid_defer.zig:3:5: note: defer expression here
defer {
^~~~~
test_errdefer.zig
const std = @import("std");
const print = std.debug.print;
// 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 {
print("\nstart of function\n", .{});
// This will always be executed on exit
defer {
print("end of function\n", .{});
}
errdefer {
print("encountered an error!\n", .{});
}
if (is_error) {
return error.DeferError;
}
}
// The errdefer keyword also supports an alternative syntax to capture the
// generated error.
//
// This is useful for printing an additional error message during clean up.
fn deferErrorCaptureExample() !void {
errdefer |err| {
std.debug.print("the error is {s}\n", .{@errorName(err)});
}
return error.DeferError;
}
test "errdefer unwinding" {
deferErrorExample(false) catch {};
deferErrorExample(true) catch {};
deferErrorCaptureExample() catch {};
}
Shell
$ zig test test_errdefer.zig
1/1 test.errdefer unwinding...
start of function
end of function
start of function
encountered an error!
end of function
the error is DeferError
OK
All 1 tests passed.
See also: