Skip to content

Commit b74812d

Browse files
committed
add defer
1 parent b7d82cb commit b74812d

File tree

5 files changed

+72
-0
lines changed

5 files changed

+72
-0
lines changed

defer/basic.zig

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const print = @import("std").debug.print;
2+
3+
pub fn main() !void {
4+
var x: u8 = 10;
5+
{
6+
defer x += 1;
7+
print("X: {}\n", .{x});
8+
}
9+
print("X: {}\n", .{x});
10+
}

defer/block.zig

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const print = @import("std").debug.print;
2+
3+
pub fn main() !void {
4+
var x: u8 = 10;
5+
{
6+
defer {
7+
x += 1;
8+
x *= 2;
9+
}
10+
print("X: {}\n", .{x});
11+
}
12+
print("X: {}\n", .{x});
13+
}

defer/function.zig

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const print = @import("std").debug.print;
2+
3+
var x: u8 = 10;
4+
5+
pub fn main() !void {
6+
foo();
7+
print("X: {}\n", .{x});
8+
}
9+
10+
fn foo() void {
11+
defer x += 1;
12+
print("X: {}\n", .{x});
13+
}

defer/multiple.zig

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const print = @import("std").debug.print;
2+
3+
pub fn main() !void {
4+
var x: u8 = 10;
5+
{
6+
defer x += 1;
7+
defer x *= 2;
8+
print("X: {}\n", .{x});
9+
}
10+
print("X: {}\n", .{x});
11+
}

defer/readme.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Defer
2+
3+
```bash
4+
$ zig run basic.zig
5+
X: 10
6+
X: 11
7+
```
8+
9+
```bash
10+
$ zig run multiple.zig
11+
X: 10
12+
X: 21
13+
```
14+
15+
```bash
16+
$ zig run block.zig
17+
X: 10
18+
X: 22
19+
```
20+
21+
```bash
22+
$ zig run function.zig
23+
X: 10
24+
X: 11
25+
```

0 commit comments

Comments
 (0)