Variable declaration at if-expression scope

Thanks - yes got it right with break. And I agree. It is in the same ballpark or solution but the original question definitely has a different intent - apologies.

BTW: I neglected the break till now in Zig, as it is a pattern in other languages that you generally can avoid with control flow. In Zig however it has much more value.

There is no need to add a break, you can just use the switch as an expression by removing the return.

    const new_age = get_switched(a) catch |err| switch (err) {
        MyError.err1 => 77,
        MyError.err2 => 88,
        MyError.err3 => 99,
    };
1 Like

Yes, you can if that control flow is wanted, my assumption was that the error case doesn’t want to continue with the rest of the function, because the first of the original examples also returned.

But you are right to point that out, because I missed that @gkell wanted an easy way to pick a fallback value from an error value and your solution demonstrates that.

   const new_age = new_age: {
        if (get_switched(a)) |age| {
            std.debug.print("New Age {}", .{age});
            break :new_age age;
        } else |err| switch (err) {
            MyError.err1 => break :new_age 77,
            MyError.err2 => break :new_age 88,
            MyError.err3 => break :new_age 99,
        }
    };
1 Like