Zig Idioms for Handling Error Unions and Optionals
I have written this post as a quick reference to remind me how to handle error unions, optionals, and the combination of an error union with an optional.
Error Union
const blah = try callFunction();
const blah = callFunction() catch 0;
const blah = callFunction() catch |error| switch (error) {
error.OutOfMemory => return,
else => 0,
};
if (callFunction()) |value| {
use(value);
} else |error| {
handle(error);
}
Optional
const blah = callFunction() orelse 0;
const blah = callFunction() orelse return;
if (callFunction()) |the_value| {
use(the_value);
} else {
defaultAction();
}
Combined Error Union with Optional
while (try callFunction()) |the_value| {
handle(the_value);
} else |the_error| {
handle(the_value);
}
Note: need to test this wrt the try.
if (callFunction()) |the_value| {
handle(the_value);
} catch |the_error| {
handle(the_error);
} else {
defaultAction();
}
Note: no idea if this works. #Zig