Control flow structures in Rust determine the execution order of statements based on conditions, loops, or patterns. These structures make your code flexible, logical, and organized. R
1. Conditional Statements
Conditional statements control the flow of execution based on conditions. Rust uses the if and else keywords to implement conditional logic.
Syntax
if condition {
// code block
} else if another_condition {
// another code block
} else {
// default code block
}
Example: Checking a Number
fn main() {
let number = 5;
if number > 0 {
println!("The number is positive.");
} else if number < 0 {
println!("The number is negative.");
} else {
println!("The number is zero.");
}
}
2. The match Expression
The match expression in Rust is a powerful and concise way to handle pattern matching. It is similar to a switch-case structure in other languages but is more versatile.
Syntax
match value {
pattern1 => action1,
pattern2 => action2,
_ => default_action,
}
Example: Matching Days of the Week
fn main() {
let day = "Monday";
match day {
"Monday" => println!("Start of the workweek."),
"Friday" => println!("Almost weekend!"),
"Saturday" | "Sunday" => println!("It's the weekend!"),
_ => println!("It's a regular day."),
}
}
Note: The _
pattern is a wildcard that matches any value not explicitly handled.
3. Loops
Rust provides three types of loops: loop, while and for.
3.1 Infinite Loops with loop
The loop keyword creates an infinite loop. You can use the break
statement to exit the loop.
Example: Loop Until Condition is Met
fn main() {
let mut count = 0;
loop {
if count == 5 {
break;
}
println!("Count: {}", count);
count += 1;
}
}
3.2 Conditional Loops with while
The while loop executes a block of code while a condition is true.
Syntax
while condition {
// code block
}
Example: Countdown
fn main() {
let mut countdown = 5;
while countdown > 0 {
println!("{} seconds remaining!", countdown);
countdown -= 1;
}
println!("Time's up!");
}
3.3 Iterating with for Loops
The for loop iterates over elements in a range or collection.
Syntax
for element in collection {
// code block
}
Example: Iterating Over a Range
fn main() {
for number in 1..=5 {
println!("Number: {}", number);
}
}
Explanation:
- 1. .=5: This range includes numbers from 1 to 5 (inclusive).
- 1. .5: This range includes numbers from 1 to 4 (exclusive of 5).
4. Early Returns with break and continue
- break: Exits the loop immediately.
- continue: Skips the rest of the current iteration and moves to the next iteration.
Example: Using continue to Skip Even Numbers
fn main() {
for number in 1..10 {
if number % 2 == 0 {
continue;
}
println!("Odd number: {}", number);
}
}
5. Combining Control Flow Structures
You can combine multiple control flow structures for complex logic.
Example: Nested Loops with Conditions
fn main() {
for x in 1..=3 {
for y in 1..=3 {
if x == y {
println!("Diagonal element: ({}, {})", x, y);
}
}
}
}