I’m currently learning Zig and I’ve come across a code example that I’m trying to understand. Here’s the code:
fn sayHelloMaybeEdOrError(name: []const u8) void {
if (dudeIsMaybeEdOrError(name)) |maybe_ed| {
if (maybe_ed) |ed| {
std.debug.print("ed? {}\n", .{ed});
if (ed) {
std.debug.print("hello {s}\n", .{name});
} else {
std.debug.print("hello again {s}\n", .{name});
}
} else {
std.debug.print("goodbye {s}\n", .{name});
}
} else |err| {
std.debug.print("got error: {}!\n", .{err});
std.debug.print("hello world!\n", .{});
}
}
From my understanding:
- The
if
statement in Zig doesn’t capture any value when used with a boolean expression. - When used with an optional (
?
) type, theif
statement captures a value only after theif
clause. - When used with an error (
!
) type, theif
statement captures a value after both theif
andelse
clauses.
I find this to be a neat syntactic sugar, but it’s a bit confusing to see the if
statement being “overloaded” in this way.