Justus’ sweet rewrite of the switch logic got merged and I think that’s an enabler for the following idiom:
const std = @import("std");
pub fn fails(fail: bool) !void {
return if (fail) error.SomeError else {};
}
pub fn main() !void {
var debug_allocator = std.heap.DebugAllocator(.{}){};
const gpa = debug_allocator.allocator();
const data = try gpa.alloc(u8, 1024);
defer gpa.free(data);
// Here we express that we disallow OOM errors going forward, but
// we do allow other errors to propagate. You can obviously
// add more prongs as needed.
// However, this feature may be removed: https://github.com/ziglang/zig/issues/23734
errdefer |err| {
switch (err) {
error.OutOfMemory => comptime unreachable,
inline else => {},
}
}
try fails(true);
}
This is a variation of errdefer comptime unreachable, but we get to cherry-pick which errors we want to block and allow. In this example, OOM can only happen above errdefer, but we allow other errors.
This won’t compile on 0.15.x due to 'error.OutOfMemory' not a member of destination error set, but it does compile on latest master after Justus’ improvements.
Anyway, I haven’t tested this in real-world code and capturing errdefer is slated for removal, but figured I’d mention it.
ok, I see, the OP’s variant is kind of like removal of that error variant from the return site from that point forward. which is real smart, sadly. just that little bit of almost magic that zig lacks everywhere else.
it can also just be reordered to be explicit and stupid. for example, by simply lacking calls that could return that error variant, and making returned error sets explicit so that you could not return it?
Well, the original snippet is just enough to express the idiom and not an example where it’s actually useful. What if you scale up?
A larger function can have SomeError in the error set (heck, maybe you’re forced to use anyerror), and it may be useful to express it’s never ever returned “from this point” through that static assertion. That’s refactor-proofing and useful information to the reader imo.
I don’t think this would ever be common, just wondering if it’s a useful tool to have.