Skip to content

Commit f79c652

Browse files
committed
add optional
1 parent e9a30fa commit f79c652

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed

optional/basic.zig

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

optional/orelse.zig

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const std = @import("std");
2+
3+
pub fn main() void {
4+
var a: ?u8 = null;
5+
const b: u8 = 32;
6+
var c = a orelse b;
7+
std.debug.print("Value: {}\n", .{c});
8+
9+
a = 128;
10+
c = a orelse b;
11+
std.debug.print("Value: {}\n", .{c});
12+
13+
std.debug.print("Type: {}", .{@TypeOf(c)});
14+
}

optional/readme.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Optional
2+
3+
```bash
4+
$ zig run basic.zig
5+
Value: null
6+
Value: 32
7+
```
8+
9+
```bash
10+
$ zig run orelse.zig
11+
Value: 32
12+
Value: 128
13+
Type: u8
14+
```
15+
16+
```bash
17+
$ zig run unreachable.zig
18+
Value: 32
19+
thread 55352 panic: attempt to use null value
20+
```

optional/unreachable.zig

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

0 commit comments

Comments
 (0)