Is there a better way to run a check for a falliable shortcut and fall back to a normal way?

This seems unreasonably terse

_ = blk: {
    if (hasShortcut()) |context|
        return canFail(context) catch break :blk {};
}

return try normalWay();

Doesn’t the return make the break useless here? That whole line looks really strange imo.

If I understood what you want correctly, this is what I would do (with braces for clarity):

if (hasShortcut()) |context| {
    if (canFail(context)) |result| {
        return result;
    } else |_| {}
}

return try normalWay();
1 Like

Two alternatives:

const context = hasShortcut() orelse return try normalWay();
return canFail(context) catch try normalWay();
fn shortcut() !T {
	const context = hasShortcut() orelse return error.NoShortcut;
	return try canFail(context);
}
...
return shortcut() catch try normalWay();
2 Likes
if (hasShortcut()) |context| if (canFail(context)) |result| 
    return result
else |_| {};

return try normalWay();

A bit verbose, but I like finding excuses to use labeled switches:

const state: union(enum) {
    start,
    can_fail: Context,
    normal,
} = .start;

return branch: switch (state) {
    .start => {
        continue :branch if (hasShortcut()) |ctx|
            .{ .can_fail = ctx }
        else
            .normal;
    },
    .can_fail => |ctx| canFail(ctx) catch continue :branch .normal,
    .normal => try normalWay(),
};