0
test "error union if" {
    var ent_num: error{UnknownEntity}!u32 = error.UnknownEntity;
    if (ent_num) |entity| {
        try expect(@TypeOf(entity) == u32);
        try expect(entity == 5);
    } else |err| {
        _ = err catch |err1| { // compiles fine when this block is removed
            std.debug.print("{s}", .{err1});
        };
        std.debug.print("{s}", .{err});
    }
}
./main.zig:125:5: error: expected error union type, found 'error:124:18'
    if (ent_num) |entity| {
    ^
./main.zig:129:17: note: referenced here
        _ = err catch |err1| {

Helin Wang
  • 4,002
  • 1
  • 30
  • 34

1 Answers1

0
  1. error:124:18 refers to the error{UnknownEntity} because it's anonymous. so prints the definition address.
  2. the if (my_var) |v| ... syntax can only be used for optional types. for Error unions you must use try or catch.
  3. try and catch can't be used for Error Set

your code would be this:

const std = @import("std");
const expect = std.testing.expect;

test "error union if" {
    var ent_num: error{UnknownEntity}!u32 = error.UnknownEntity;
    const entity: u32 = ent_num catch |err| {
        std.debug.print("{s}", .{err});
        return;
    };

    try expect(@TypeOf(entity) == u32);
    try expect(entity == 5);
}

reading the programs or libraries is very useful for learning a new language. gl

Ali Chraghi
  • 613
  • 6
  • 16
  • Thanks Ali, your explanation makes sense. One follow up question - why `if (ent_num) |entity| {` shows up in the compile error? Afaik that line is correct, ent_num is of type error union. – Helin Wang Nov 29 '21 at 15:22
  • Another question, you mentioned "try and catch can only be used for Error Union, not Error Set", why does `_ = err catch {};` works instead? The example is in https://ziglearn.org/chapter-1/#payload-captures, you can find it by searching for `_ = err catch {};`. – Helin Wang Nov 29 '21 at 15:28
  • sorry my bad. you can use `if`, `else` for error unions but can't understand how's `_ = error catch {}` works with error set. but still sure it's wrong. – Ali Chraghi Nov 29 '21 at 15:42
  • Nit: I think the `err` in `err catch {};` is of type error, not error set. – Helin Wang Nov 29 '21 at 15:53
  • Maybe `expr catch {}` without capture just works with any expression that evaluates to error value. – Helin Wang Nov 29 '21 at 15:53
  • `_ = err catch {}` is odd; at this point in the program (inside the `else |err| {}` block) you already know `err` is an error, so you wouldn't need to apply the `catch` operator, which is supposed to extract the error value from an error union. – Wtrmute Jan 27 '22 at 18:35