Conditional statements in Rust allow you to execute different blocks of code based on certain conditions. The basic syntax for if statements is as follows:
let number = 10;
if number > 0 {
println!("Number is positive");
} else if number < 0 {
println!("Number is negative");
} else {
println!("Number is zero");
}- The
ifstatement checks the condition and executes the block of code if the condition is true. - The
else ifstatement allows you to check additional conditions if the previous condition is false. - The
elsestatement is optional and executes if none of the previous conditions are true.
In Rust, the if expression can be used on the right side of a let statement to conditionally assign a value to a variable. This allows for concise and readable code that assigns different values based on a condition.
Example:
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}Pattern matching in Rust provides a concise way to compare values against a series of patterns and execute code based on the matched pattern. Here's an example:
let number = 42;
match number {
0 => println!("Zero"),
1 => println!("One"),
_ => println!("Other"),
}- The
matchkeyword is followed by the value to match against. - Each arm of the match consists of a pattern followed by the
=>operator and the code to execute if the pattern matches. - The
_wildcard pattern matches any value and is often used as a catch-all case.
Rust provides several looping constructs for executing code repeatedly.
The loop keyword creates an infinite loop that continues until explicitly interrupted with a break statement.
let mut counter = 0;
loop {
println!("Counter: {}", counter);
counter += 1;
if counter >= 10 {
break;
}
}NOTE: To return value in loop, you can add the value you want returned after the break expression you use to stop the loop; that value will be returned out of the loop. Example: break counter; in above example.
The while loop executes a block of code as long as the specified condition is true.
let mut counter = 0;
while counter < 10 {
println!("Counter: {}", counter);
counter += 1;
}The for loop iterates over elements of an iterator.
let numbers = [1, 2, 3, 4, 5];
for number in numbers.iter() {
println!("Number: {}", number);
}- The
breakstatement exits the current loop immediately. - The
continuestatement skips the rest of the current iteration and proceeds to the next iteration of the loop.
- Rust's
forloop is particularly useful for iterating over collections like arrays, vectors, and ranges. - You can also use iterators, which provide a powerful way to work with sequences of elements in Rust.
- Use
if,else if, andelsefor simple conditional branching, andmatchfor more complex pattern matching scenarios. - Prefer
forloops and iterators for iterating over collections, as they are more concise and idiomatic in Rust. - Use
loopwhen you need to create an infinite loop with explicit exit conditions.
Imagine you're developing a text adventure game in Rust. You use conditional statements to handle different player choices and looping constructs to manage game flow and interactions.
Understanding control flow constructs in Rust is essential for writing expressive and efficient code. By mastering these concepts, you'll have the tools to build complex algorithms and applications with confidence.