Rust break and continue

www.igif‮.aedit‬com

In Rust, you can use the break and continue keywords to control the flow of loops.

break allows you to exit a loop early, regardless of whether the loop condition has been met. Here's an example:

let mut count = 0;

loop {
    println!("Count is {}", count);
    count += 1;

    if count == 10 {
        break;
    }
}

In this example, we're using a loop instead of a while or for loop. Inside the loop, we're printing the current value of count and then incrementing it by 1. However, once count reaches 10, we're using the break keyword to exit the loop early.

continue allows you to skip over the rest of the current iteration of the loop and move on to the next one. Here's an example:

for num in 0..10 {
    if num % 2 == 0 {
        continue;
    }

    println!("Odd number: {}", num);
}

In this example, we're using a for loop to iterate over a range of numbers from 0 to 9 (inclusive). However, if the current number is even (i.e. its remainder when divided by 2 is 0), we're using the continue keyword to skip over the rest of the loop iteration and move on to the next number. If the current number is odd, we're printing it using the println! macro.