Inferred error set without an error union

If a function returns an error union, Zig can infer the error set automatically. Does this also somehow work for functions that don’t return error unions, but just errors?

For example, is there a way to avoid having to explicitly specify the error{ A, B } error set here?

fn mapError(x: i32) error{ A, B } {
    return if (x > 0) error.A else error.B;
}

Errors coerce to error unions, so potentially you could change the return type to !void or !noreturn?

1 Like

this should work, I think:

fn mapError(x: i32) anyerror {
    return if (x > 0) error.A else error.B;
}

Yeah I mean you can specify it wherever, check the first example here.

Specifically, there is a function down there that exclusively returns a defined error set, which I think is what you are asking for.

Edit: for convenience

const FileOpenError = error{
    AccessDenied,
    OutOfMemory,
    FileNotFound,
};

fn foo(err: AllocationError) FileOpenError {
    return err;
}

!void or !noreturn is not the same though; with that I cannot return the result directly from a function that normally returns a different type, for example

fn caller(y: i32) error{ A, B }!i32 {
    return if (y > 100) y else mapError(y);
}

(anyerror also wouldn’t work here, because “global error set cannot cast into a smaller set”.)

But with !noreturn at least it works when I call it with try, as return if (y > 100) y else try mapError(y);