-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_defer.zig
More file actions
88 lines (74 loc) · 2 KB
/
test_defer.zig
File metadata and controls
88 lines (74 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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 basic" {
try expect(try deferExample() == 5);
}
// if multiple defer statements are specified, they will be execute in
// the reverse order they were run.
fn deferUnwindExample() void {
defer {
print("1 \n", .{});
}
defer {
print("2 \n", .{});
}
if (false) {
// derfers are not run if they are never executed.
defer {
print("3 ", .{});
}
}
}
test "defer unwinding" {
deferUnwindExample();
}
// Inside a defer expression the return statement is not allowed
fn deferInvalidExample() !void {
defer {
// return error.DeferError;
}
return error.DeferError;
}
// The errdefer keyword is similar to derfer, 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 tacting tactics as seen in c.
fn deferErrorExample(is_error: bool) !void {
print("\nstart of function\n", .{});
// This will always be excuted 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 {};
}