New in Rust 1.65, break from labeled blocks

I just saw the announcement of the release of the new Rust 1.65.
A new feature is: break from labeled blocks

break from labeled blocks

Plain block expressions can now be labeled as a break target, terminating that block early. This may sound a little like a goto statement, but it’s not an arbitrary jump, only from within a block to its end. This was already possible with loop blocks, and you may have seen people write loops that always execute only once, just to get a labeled break.

Now there’s a language feature specifically for that! Labeled break may also include an expression value, just as with loops, letting a multi-statement block have an early “return” value.

let result = 'block: {
    do_thing();
    if condition_not_met() {
        break 'block 1;
    }
    do_next_thing();
    if condition_not_met() {
        break 'block 2;
    }
    do_last_thing();
    3
};

This reminded me of a thread I started in Feb 2022: Elegant breaking from nested loops.

I find it interesting (funny) that the pedantic Rust devs seemingly folded to pressure to add this,
or maybe it was just a logical addition after surfeit technical analysis. :smile:

1 Like

Check the following code basically meet same issue with you.

1 Like

I remember using an independent language called Nelua that let you create arbitrary blocks with scopes using do…end and I thought it was a nice touch

do
    #some code
end

I’m not sure if it would be easy for crystal to implement based on how it currently uses them, or difficult.

1 Like

Nelua looks like a very cool Lua variant. My son is learning another Lua variant ‘Luau’ for Roblox. :star_struck: