Control flow is a fundamental concept in Rust programming. It allows developers to direct the execution path of their code based on conditions and repetitions. Understanding control flow is crucial for writing efficient and logical Rust programs.
If statements in Rust enable conditional execution of code blocks. They evaluate a boolean expression and execute the corresponding block if the condition is true.
let number = 5;
if number < 10 {
println!("The number is less than 10");
} else if number == 10 {
println!("The number is exactly 10");
} else {
println!("The number is greater than 10");
}
Rust provides several types of loops for repetitive tasks:
The loop
keyword creates an infinite loop that can be broken using the break
statement.
let mut counter = 0;
loop {
println!("Counter: {}", counter);
counter += 1;
if counter == 5 {
break;
}
}
While loops continue executing as long as a condition remains true.
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
For loops iterate over elements in a collection or a range.
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!!");
The match
expression in Rust provides powerful pattern matching capabilities. It's similar to a switch statement in other languages but offers more flexibility and safety.
let dice_roll = 3;
match dice_roll {
3 => println!("You rolled a three!"),
7 => println!("Lucky seven!"),
_ => println!("You rolled something else"),
}
break
to exit a loop early and continue
to skip to the next iteration.match
expression must be exhaustive, covering all possible cases.Mastering control flow is essential for writing efficient Rust code. It allows you to create more complex and dynamic programs. As you progress, you'll find these concepts integrating seamlessly with other Rust features like ownership and pattern matching.
For more advanced control flow techniques, explore iterators and Result enum for error handling. These concepts build upon the foundational control flow structures and provide more sophisticated ways to manage program execution in Rust.