Optionals in Zig
?u32 is a berth number or null, and the compiler will not let you forget which.
const std = @import("std");
fn findBerth(ship: []const u8) ?u32 {
if (std.mem.eql(u8, ship, "Persephone")) return 9;
return null;
}
pub fn main() void {
// ?u32 holds a number or null; if unwraps it by capture.
if (findBerth("Persephone")) |berth| {
std.debug.print("moor at berth {d}\n", .{berth});
}
// orelse supplies the value for the null case.
const anchorage = findBerth("Dreadnought") orelse 0;
std.debug.print("unknown ships anchor at {d}\n", .{anchorage});
}
How it works
?u32in the return type admitsnullas an honest answer.if (findBerth(...)) |berth|unwraps by capture only when a value exists.orelse 0supplies the anchorage for ships the harbor does not know.
Keywords and builtins used here
constfniforelsepubreturnu32u8void
The run, in numbers
- Lines
- 17
- Characters to type
- 471
- Tokens
- 117
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 100 seconds.
Step 1 of 3 in Optionals & pointers, step 10 of 27 in Language basics.