July 27, 2026, 11:08pm 1
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;
}
alanza July 27, 2026, 11:13pm 2
Errors coerce to error unions, so potentially you could change the return type to !void or !noreturn?
lufe July 27, 2026, 11:20pm 3
this should work, I think:
fn mapError(x: i32) anyerror {
return if (x > 0) error.A else error.B;
}
Tekla July 27, 2026, 11:21pm 4
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;
}
dpirch July 27, 2026, 11:41pm 5
!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);
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.