Rust Break Statement

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

rust_break_statement

Syntax:-

Example:-

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_break_statement

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:-

When we run this code, our output will be as follows –

Output:-

rust_labeled_break_statement

In this tutorial we have learn about the Rust Break Statement and its application with practical example. I hope you will like this tutorial.