catch and orelse in Zig
Two fallback operators: catch for error unions, orelse for optionals.
const std = @import("std");
pub fn main() void {
// parseInt returns an error union; catch supplies the fallback.
const good = std.fmt.parseInt(i32, "42", 10) catch 0;
const bad = std.fmt.parseInt(i32, "4x2", 10) catch 0;
std.debug.print("good {d}, bad fell back to {d}\n", .{ good, bad });
// orelse does the same job for optionals.
const found = std.mem.indexOf(u8, "causeway", "use");
const at = found orelse 999;
std.debug.print("'use' found at index {d}\n", .{at});
}
How it works
parseInt(...) catch 0swallows the parse failure and supplies zero.- The good string parses; the bad one falls back, both in one shape.
orelsedoes the identical job when the missing thing is null, not an error.
Keywords and builtins used here
catchconstfni32orelsepubu8void
The run, in numbers
- Lines
- 13
- Characters to type
- 474
- Tokens
- 123
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 105 seconds.
Step 2 of 3 in Errors, step 8 of 27 in Language basics.