Can you define your use of DP here? I'm not sure if you mean dynamic programming, or design pattern or something else, and am curious about your insight.
fn someFunction(a: usize) MyError!usize {
if (a < 10) return error.LessThanTen;
const b = try anotherFunction(a);
return 2 * b;
}
fn anotherFunction(x: usize) MyError!usize {
if (x < 20) return error.LessThanTwenty;
return x * 3;
}
const MyError = error {
LessThanTen,
LessThanTwenty
}
> That feels very limiting, I often use error types to e.g., attach data about the error. Is there a more general mechanism for sum types for when this shorthand doesn't apply? fn parse(allocator: *mem.Allocator, tokens: Tokens, parse_error: *ParseError) !AST
The `parse_error` can be set if an error condition occurs. I concede that that's a little clumsy Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. @import returns the struct type corresponding to the file.
This means that there isn't really any difference between accessing a struct field and accessing something in module...the module is also a kind of struct (and rust, as in zig, differentiating struct field access vs function invocation is possible because of the parens in the latter). 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. Result<Option<usize>, Error>>
in rust is rendered (mostly) equivalently in zig as !?usize
Note: there are some options in rust for cleaning up errors such as the anyhow library. var it = mem.split(...);
// it.next() returns null after we run out of
// split text and the while loop exits
while (it.next()) |substr| {
// In here we have a non-nil substr
}
> Plus I imagine it's a lot easier for the compiler to perform optimizations this way.