Break and Continue are two essential control statements that offer powerful control inside a loop.
The break statement is used to exit a loop immediately, without waiting for the loop to be met or for a specific condition to be met. For example: “break” is a stop sign that the loop ends instantly when Rust see it.
Syntax:
break;
It is commonly used with:
- Infinite loops (loop)
- while and for loops
- match expressions (with labels)
Example 1: Stop When Secret Code is Found
fn main() {
let secret_code = 7;
let guesses = [1, 3, 5, 7, 9];
for code in guesses {
if code == secret_code {
println!("Secret code {} found!", code);
break;
}
println!("{} is not the secret code.", code);
}
}
Output:
1 is not the secret code.
3 is not the secret code.
5 is not the secret code.
Secret code 7 found!
You can see that the loop stops running as soon as the secret code is matched.
What is Continue Statement in Rust?
The continue statement is used to skip the current iteration and move to the next one. It does not stop the entire loop; it just says: “Skip this round and go again.”
Syntax:
continue;
Example 2: Skip Negative Numbers While Summing the numbers
fn main() {
let numbers = [5, -3, 8, -1, 4];
let mut total = 0;
for num in numbers {
if num < 0 {
continue;
}
total += num;
}
println!("Sum of positive numbers: {}", total);
}
Output:
Sum of positive numbers: 17
Here, the loop skips the negative numbers using the continue statement and only adds positive values to the total.
How to Use Break and Continue with Labels
Rust allows us to use labels with loops. This is useful when you have nested loops and want to control which loop to break or continue.
Example 3: Find First Even Number in Nested Loop
fn main() {
let matrix = vec![
vec![1, 3, 5],
vec![7, 8, 9],
vec![11, 13, 15],
];
'outer: for row in &matrix {
for &num in row {
if num % 2 == 0 {
println!("First even number found: {}", num);
break 'outer;
}
}
}
}
Output:
First even number found: 8
Here, break ‘outer; stops both inner and outer loops after finding the first even number.
Simple Exercise for Practice:
Task:
Create a program that checks numbers from 1 to 10 and performs the following tasks:
- Skips even numbers using the continue statement
- Stops if it encounters the number
7
using break
Output of this exercise:
1
35
Tip for learners:
Try rewriting these examples in your style. Change the data, tweak the conditions, and observe how break and continue behave differently; that’s the best way to master control flow in Rust.