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

4

1 回答 1

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

你的代码是这样的:

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

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

于 2021-11-29T09:28:59.410 回答