Errors union should allow compiler to see underlying type. Right?

Sorry for stupid topic name. Couldn’t imagine anything better.

const S1 = struct {
    a: u32,
    pub fn init() @This() {
        return .{ .a = 5 };
    }
};

const S2 = struct {
    a: u32,
    pub fn init() anyerror!@This() {
        return .{ .a = 5 };
    }
};

pub fn main() void {
    const s1: S1 = .init(); //ok
    const s2: S2 = .init() catch unreachable; // error: type '@EnumLiteral()' not a function
}

So the problem is simple when you have error union compiler struggles to kinda infer type and disallows neat “stripped” syntax (I would appreciate a name of this syntax in replies). So I want to know if it is intended design and it is me being dumb or I should go and create issue?

It’s a limitation of the current type system. Has been discussed and is well known by the core team. The result type doesn’t flow through catch because unlike other operators, it can’t infer which error type should be present. There’s some possible solutions, I’d like to see one implemented at some point, but it’s not a burning priority.

4 Likes