In Rust, break and continue are control flow keywords used within loops (loop, while and for) to alter the flow of execution.
What is the break Statement?
The break statement is used to exit a loop immediately, regardless of its condition. When a break is encountered, the control flow jumps out of the loop, resuming execution with the statement following the loop.
Syntax of break
loop {
// Some code
if condition {
break; // Exit the loop
}
}
Examples of break
Example 1: Exiting a Loop When a Condition is Met
fn main() {
let mut counter = 0;
loop {
counter += 1;
println!("Counter: {}", counter);
if counter == 5 {
break; // Exit the loop when counter reaches 5
}
}
println!("Loop exited");
}
Output:
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Loop exited
Example 2: Using break in a for Loop
fn main() {
for num in 1..10 {
if num == 4 {
break; // Exit the loop when num equals 4
}
println!("Number: {}", num);
}
}
Output:
Number: 1
Number: 2
Number: 3
What is the continue Statement?
The continue statement skips the remaining part of the current loop iteration and proceeds directly to the next iteration. It does not terminate the loop but prevents the execution of further statements within the current iteration.
Syntax of continue
for item in collection {
if condition {
continue; // Skip this iteration
}
// Code executed if the condition is false
}
Examples of continue
Example 1: Skipping Iterations
fn main() {
for num in 1..6 {
if num % 2 == 0 {
continue; // Skip even numbers
}
println!("Odd number: {}", num);
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Example 2: Using continue in a while Loop
fn main() {
let mut num = 0;
while num < 5 {
num += 1;
if num == 3 {
continue; // Skip iteration when num equals 3
}
println!("Number: {}", num);
}
}
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Combining break and continue
You can use both break and continue within the same loop to manage complex logic.
Example: Combining break and continue
fn main() {
for num in 1..10 {
if num % 2 == 0 {
continue; // Skip even numbers
}
if num == 7 {
break; // Exit the loop when num equals 7
}
println!("Odd number: {}", num);
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Labels with break and continue
Rust allows labeling loops to differentiate between multiple nested loops. You can specify which loop to break or continue by referencing its label.
Example: Using Labels
fn main() {
'outer: for i in 1..4 {
for j in 1..4 {
if i == j {
continue 'outer; // Skip to the next iteration of the outer loop
}
if i + j == 5 {
break 'outer; // Exit the outer loop
}
println!("i: {}, j: {}", i, j);
}
}
}
Output:
i: 1, j: 2
i: 2, j: 1
Use Cases of break and continue
- break:
- Exiting loops early when a condition is satisfied.
- Ending infinite loops (loop keyword).
- Returning values from a loop using break.
- continue:
- Skipping iterations based on conditions.
- Optimizing loop execution by bypassing unnecessary code.