-
Notifications
You must be signed in to change notification settings - Fork 0
/
defer.zig
71 lines (59 loc) · 1.44 KB
/
defer.zig
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
const assert = @import("std").debug.assert;
const printf = @import("std").io.stdout.printf;
// 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;
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() {
%%printf("\n");
defer {
%%printf("1 ");
}
defer {
%%printf("2 ");
}
if (false) {
// defers are not run if they are never executed.
defer {
%%printf("3 ");
}
}
}
test "defer unwinding" {
deferUnwindExample()
}
// The %defer keyword is similar to defer, but will only execute if the
// function 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.
error DeferError;
fn deferErrorExample(is_error: bool) -> %void {
%%printf("\nstart of function\n");
// This will always be executed on exit
defer {
%%printf("end of function\n");
}
%defer {
%%printf("encountered an error!\n");
}
if (is_error) {
return error.DeferError;
}
}
test "%defer unwinding" {
_ = deferErrorExample(false);
_ = deferErrorExample(true);
}