Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Break out of specific loop and return a value

I have just started studying Rust and reaching the control flow section I read break can return a value (the loop is an expression) and it can also break out of a specific loop using a label, e.g. break 'counting_up.

So my question is:

Is it possible to combine the two? i.e. break out of a specific loop by naming it and return a value as well?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If so, what is the syntax for assigning + declaring the loop?

What is the syntax of the break?

The following are two possibilities, but neither syntax compiles:

fn main() {
    let mut count = 0;
    // would this do?
    let result = 'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                // break count*10, 'counting_up;
                // or should it be:
                break 'counting_up, count*10;
            }
            remaining -= 1;
        }

        count += 1;
    };
    println!("End count = {count}");
}

>Solution :

Yes it is, and there is no separator, just break 'label value:

fn main() {
    let mut count = 0;
    let result = 'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up count*10;
            }
            remaining -= 1;
        }

        count += 1;
    };
    println!("End count = {count}");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading