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. Well, more accurately ...I started this post for that reason, but in truth it has led me to better understand these language features.

Optional

We will start the journey with optionals, which can be either a value or null.

When using an optional in an expression, we can use orelse to simultaneously unwrap a non-null value and to provide a default value.

And when using vertical bars to capture a non-null value within an if or while statement, we can use else to handle the null value.

test "test optional" {
    // orelse
    try std.testing.expectEqual(true, generateOptional(.VALUE) orelse false);
    try std.testing.expectEqual(false, generateOptional(.NULL) orelse false);
    try std.testing.expectEqual(false, generateOptional(.ERROR) orelse false);
    // if else
    try std.testing.expectEqual(true, 
        if (generateOptional(.VALUE)) |the_value| the_value else false);
    try std.testing.expectEqual(false, 
        if (generateOptional(.NULL)) |the_value| the_value else false);
    try std.testing.expectEqual(false, 
        if (generateOptional(.ERROR)) |the_value| the_value else false);
    // while
    try std.testing.expectEqual(true, 
        blk: while (generateOptional(.VALUE)) |the_value| break :blk the_value 
            else break :blk false);
    try std.testing.expectEqual(false, 
        blk: while (generateOptional(.NULL)) |the_value| break :blk the_value 
            else break :blk false);
    try std.testing.expectEqual(false, 
        blk: while (generateOptional(.ERROR)) |the_value| break :blk the_value 
            else break :blk false);
}

Error Union

The error union has catch as the counterpoint to optional's orelse within expressions, and catch can be used with or without vertical bars capturing the actual error.

But life gets confusing when we switch to if and while statements as the same else clause (as used by optionals) takes the place of catch. This is covered by the language documentation though, which makes it clear that else with a vertical bar capture requires the condition to have an error union type.

test "test error union" {
    // simple catch
    try std.testing.expectEqual(true, generateErrorUnion(.VALUE) catch false);
    try std.testing.expectEqual(false, generateErrorUnion(.NULL) catch false);
    try std.testing.expectEqual(false, generateErrorUnion(.ERROR) catch false);
    // catch with capture
    try std.testing.expectEqual(true, generateErrorUnion(.VALUE) catch |err| switch (err) {
        TestError.ExpectedError => false,
        else => false,
    });
    try std.testing.expectEqual(false, generateErrorUnion(.NULL) catch |err| switch (err) {
        TestError.UnexpectedError => false,
        else => true,
    });
    try std.testing.expectEqual(false, generateErrorUnion(.ERROR) catch |err| switch (err) {
        TestError.ExpectedError => false,
        else => true,
    });
    // if with capture, else with capture
    try std.testing.expectEqual(true, if (generateErrorUnion(.VALUE)) |the_value| the_value else |err| switch (err) {
        TestError.ExpectedError => false,
        else => false,
    });
    try std.testing.expectEqual(false, if (generateErrorUnion(.NULL)) |the_value| the_value else |err| switch (err) {
        TestError.UnexpectedError => false,
        else => true,
    });
    try std.testing.expectEqual(false, if (generateErrorUnion(.ERROR)) |the_value| the_value else |err| switch (err) {
        TestError.ExpectedError => false,
        else => true,
    });
    // while
    try std.testing.expectEqual(true, blk: while (generateErrorUnion(.VALUE)) |the_value| break :blk the_value else |err| break :blk switch (err) {
        TestError.ExpectedError => false,
        else => false,
    });
    try std.testing.expectEqual(false, blk: while (generateErrorUnion(.NULL)) |the_value| break :blk the_value else |err| break :blk switch (err) {
        TestError.UnexpectedError => false,
        else => false,
    });
    try std.testing.expectEqual(false, blk: while (generateErrorUnion(.ERROR)) |the_value| break :blk the_value else |err| break :blk switch (err) {
        TestError.ExpectedError => false,
        else => false,
    });
}

Combined Error Union with Optional

The combination of error union and optional I struggle with handling elegantly, well particularly when not using try (e.g., when I want to map from one error code to another, or when I want to react to explicitly handle an error).

The golden rule is that the error union envelops the optional, and so must be unwrapped first. Consequently, the else prong of an if or while statement (where the condition is an error union wrapping an optional) must be for the error case and so should have vertical bars capturing the error. And the unwrapped non-error value is still an optional.

test "error union optional" {
    // using try
    try std.testing.expectEqual(true, 
        try generateErrorUnionOptional(.VALUE) orelse false);
    // else must have capture
    try std.testing.expectEqual(true, 
        if (generateErrorUnionOptional(.VALUE)) |the_value| the_value 
            orelse false 
        else |the_err| switch (the_err) {
            else => false,
        });
}

Note: I kinda would have liked to see an if () |value| ... else |err| ... else ... construct to handle the value, the error and the null (respectively), but there's probably legitimate reasons for its absence.

#Zig