defer
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();
}
// 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", .{});
}
// inside a defer method the return statement
// is not allowed.
// The following lines produce the following
// error if uncomment
//
// defer.zig:73:9: error: cannot return from defer expression
// return error.DeferError;
// ```
//
//defer {
// return error.DeferError;
//}
if (is_error) {
return error.DeferError;
}
}
// The errdefer keyword support also an alternative syntax to capture the // error generated in case of one error. // // This is useful when during the clean up after an error additional // message want to be printed. 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 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 the error is DeferError OK All 3 tests passed. ```
See also: