In this tutorial you will learn about the Rust Break Statement and its application with practical example.
Rust Break Statement
In Rust, break statement inside any loop gives you way to break or terminate the execution of loop containing it, and transfers the execution to the next statement following the loop. It is almost always used with if construct.
Rust Break Statement Flow Diagram
Syntax:-
1 |
break; |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fn main(){ let mut ctr = 0; println!("W3Adda - Rust Break Statement"); while ctr <= 10 { ctr = ctr + 1; if ctr == 5 { break; } println!("Inside loop {}", ctr); } println!("Out of while loop"); } |
In this above program, the variable ctr is initialized as 0. Then a while loop is executed as long as the variable ctr is less than 10. Inside the while loop, the ctr variable is incremented by 1 with each iteration (ctr = ctr + 1). Next, we have an if statement that checks the variable ctr is equal to 5, if it return TRUE causes loop to break or terminate. Within the loop there is a println!() statement that will execute with each iteration of the while loop until the loop breaks. Then, there is a final println!() statement outside of the while loop.
When we run this code, our output will be as follows –
Output:-
Rust Labeled break
In Rust, sometimes you may encounter situations where you have nested loops, in such case you are required to specify the loop which one your break
statement is applicable for. The standard unlabeled break statement is used to terminates the nearest enclosing loop. In Rust, there is another form of break (labeled break) statement is used to terminate specified loop and control jumps to the statement immediately following the labeled statement. In such cases, the loops must be annotated with some ‘label, which is passed to the break statement.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#![allow(unreachable_code)] fn main() { println!("W3Adda Rust Labeled break Statement"); 'outer: loop { println!("Entered the outer loop"); 'inner: loop { println!("Entered the inner loop"); // This breaks the outer loop break 'outer; } println!("This point will never be reached"); } println!("Exited the outer loop"); } |
When we run this code, our output will be as follows –
Output:-