Helin Wang
Helin Wang

Reputation: 4202

Why does this zig program fail to compile due to "expected error union type, found 'error:124:18'"?

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| {

Upvotes: 2

Views: 4143

Answers (1)

Ali Chraghi
Ali Chraghi

Reputation: 839

  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

Upvotes: 0

Related Questions