Control Structures in Rust
Control structures in Rust allow you to control the flow of your program. They include conditional statements (if-else), loops (for, while, loop), and pattern matching (match).
If-Else Statements
The if-else
statement is used to execute a block of code based on a condition.
fn main() {
let age = 20;
if age >= 18 {
println!("You are an adult.");
} else {
println!("You are a minor.");
}
}
Loops
Loops are used to execute a block of code repeatedly. Rust supports for
, while
, and loop
.
fn main() {
// For Loop
for i in 0..5 {
println!("{}", i);
}
// While Loop
let mut count = 0;
while count < 5 {
println!("{}", count);
count += 1;
}
// Infinite Loop
loop {
println!("This will run forever!");
break; // Exit the loop
}
}
Pattern Matching with match
The match
expression is a powerful control structure that allows you to compare a value against a series of patterns.
fn main() {
let number = 3;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Other"),
}
}
Loop Labels
Rust allows you to label loops, which can be useful for breaking or continuing outer loops from within nested loops.
fn main() {
'outer: loop {
println!("Entered the outer loop");
'inner: loop {
println!("Entered the inner loop");
break 'outer; // Break the outer loop
}
}
println!("Exited the outer loop");
}
Break and Continue
Use break
to exit a loop and continue
to skip the current iteration.
fn main() {
for i in 0..10 {
if i == 5 {
continue; // Skip the rest of the loop for i = 5
}
if i == 8 {
break; // Exit the loop when i = 8
}
println!("{}", i);
}
}
Best Practices
- Prefer
match
over nestedif-else
:match
is more readable and safer. - Use Loop Labels Sparingly: They can make code harder to read if overused.
- Avoid Infinite Loops: Ensure loops have a clear exit condition.
- Keep Conditions Simple: Complex conditions can make code harder to understand.