DEV Community

Discussion on: Did you know that JavaScript has had labels since ES3?!?

Collapse
 
benaryorg profile image
#benaryorg • Edited

This is actually a thing in Rust too.
Just that in Rust it is actually being used.

The best example is breaking out of nested loops:

#![allow(unreachable_code)]

fn main() {
    'outer: loop {
        println!("Entered the outer loop");

        'inner: loop {
            println!("Entered the inner loop");

            // This would break only the inner loop
            //break;

            // This breaks the outer loop
            break 'outer;
        }

        println!("This point will never be reached");
    }

    println!("Exited the outer loop");
}

(taken from rustbyexample.com)

Edit: Imagine for example a "mainloop". Usually it's a while running where running is a global mutable variable or something.
In Rust you don't need that condition, you can just break out of the outer loop.

Edit 2: This is especially useful since blocks in Rust can return a value. This way you can use a loop and break out of it with a value.
This is comparable to inlining a function that contains a loop and returns.