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

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

  1. error:124:18 指的是 error{UnknownEntity} 因为它是 匿名的。所以打印定义地址。
  2. if (my_var) |v| ...语法只能用于可选 类型。对于 错误联合 你必须使用 trycatch.
  3. trycatch 不能用于 错误设置

你的代码应该是这样的:

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);
}

阅读程序或库对于学习一门新语言非常有用。 gl