Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/defer.zig

89 lines
1.9 KiB

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
// defer is used to defer execution till the end of the scope - the order is that of a stack - LIFO. This means that the first defer statement
// will be executed last.
test "basic defer" {
defer debug.print("This will be seen last\n", .{});
{
defer debug.print("This will be seen second last\n", .{});
{
defer debug.print("This will be seen second\n", .{});
{
defer debug.print("This will be seen first\n", .{});
}
}
}
}
fn deferExample() i32 {
var a: i32 = 1;
{
defer a = 2;
a = 1;
}
testing.expectEqual(a, 2);
a = 5;
return a;
}
test "basic defer function example" {
testing.expectEqual(deferExample(), 5);
}
fn deferUnwindExample() void {
debug.print("\n", .{});
defer {
debug.print("1 ", .{});
}
defer {
debug.print("2 ", .{});
}
if (false) {
defer {
debug.print("This is never printed", .{});
}
}
}
test "defer unwind example" {
deferUnwindExample();
}
// errdefer is a variant of defer which is run only when the scope returns with an error. When there are multiple errdefers in a scope,
// they are again run in the opposite order of being declared.
fn deferErrorExample(is_error: bool) !void {
debug.print("\nStart of function\n", .{});
defer {
debug.print("End of function\n", .{});
}
errdefer {
debug.print("Wished the error all the best!\n", .{});
}
errdefer {
debug.print("Acknowledged the error\n", .{});
}
errdefer {
debug.print("Encountered an error\n", .{});
}
if (is_error) {
return error.DeferError;
}
}
test "errdefer example" {
deferErrorExample(false) catch {};
deferErrorExample(true) catch {};
}