|
|
|
|
|
by malcolmstill
1203 days ago
|
|
So usually you don't have to specify the error type. The Zig compiler works out what errors are returned from the function by looking at any errors returned directly or errors returned from other functions called within the body of the function. That set of errors forms an enum that is the actual error type, you just don't have to write that out explicitly. An example might be: fn someFunction(a: usize) !usize {
if (a < 10) return error.LessThanTen;
const b = try anotherFunction(a);
return 2 * b;
}
fn anotherFunction(x: usize) !usize {
if (x < 20) return error.LessThanTwenty;
return x * 3;
}
The compiler infers the error type of `someFunction` as: error {
LessThanTen,
LessThanTwenty
}
When you then `switch` on an error type, the compiler will exhaustively check that you have handled all the cases.Note the "(mostly) equivalently" was a reference to the fact that Zig errors can't (currently) contain any other information, whereas an error in rust can carry other information. Also note that the compiler can't infer the error type in all case, for example in the case of a recursive function. In that case you do need to explicitly write out the error set. |
|
1. Doesn't that risk introducing accidental breaking changes by adding a new error to the set in the implementation, since the set of errors is inferred from the implementation? Having a compile error in this case in Rust is often the last barrier standing between me and an accidental major semver bump (since callers have to exhaustively match on the error conditions) 2. Can you have data in the variants of the error enumeration?