This chapter delves into rust-control-flow , a fundamental concept for directing the execution of code based on conditions, iterations, and branching logic. Rust’s control flow constructs enable developers to write flexible, efficient, and robust programs by determining the sequence and repetition of statements.
Chapter Goal
- Understand the role of control flow in structuring Rust programs.
- Learn the syntax and use cases of control flow constructs.
- Explore practical examples of conditional statements and loops in Rust.
Key Characteristics of Control Flow
- Control flow enables decision-making, repetition, and branching logic in programs.
- Rust offers if, match, and looping constructs for different use cases.
- Ensures memory safety and prevents common issues like infinite loops.
Best Practices
- Use if statements for simple conditions.
- Opt for match for exhaustive pattern matching.
- Ensure loop conditions are well-defined to prevent infinite loops.
- Use break and continue judiciously to manage loop flow.
- Leverage Rust’s ownership and borrowing rules within control flow to prevent errors.
Syntax Table
Serial No | Construct | Syntax Example | Description |
1 | If | if condition { … } | Executes code block if condition evaluates to true. |
2 | If-Else | if condition { … } else { … } | Executes one of two blocks based on the condition. |
3 | Else If | if condition { … } else if condition { … } | Chains multiple conditions for decision-making. |
4 | Match | match value { … } | Evaluates a value and matches it against patterns. |
5 | Loop | loop { … } | Creates an infinite loop, terminated with break. |
6 | While | while condition { … } | Repeats code while the condition is true. |
7 | For | for item in iterable { … } | Iterates over a collection or range. |
Syntax Explanation
1. If Statement
What is If?
The if statement evaluates a condition and executes the corresponding block of code if the condition is true. It is a cornerstone of decision-making in Rust.
Syntax
if condition {
// Code block
}
Detailed Explanation
- Executes the code block if the condition evaluates to true.
- Does not execute the block if the condition is false.
- The condition must return a boolean value (bool).
Example
let number = 10;
if number > 5 {
println!(“The number is greater than 5.”);
}
Example Explanation
- The program first evaluates the condition number > 5.
- Given that the value of number is 10, the condition evaluates to true.
- Since the condition is true, the block inside the if statement executes.
- The program prints the message “The number is greater than 5.” to the console, confirming that the condition was satisfied.
2. If-Else Statement
What is If-Else?
The if-else statement provides an alternate code block to execute when the if condition evaluates to false.
Syntax
if condition {
// Code block if true
} else {
// Code block if false
}
Detailed Explanation
- Allows execution of one of two code blocks based on the condition.
- Ensures that exactly one block is executed.
Example
let number = 3;
if number > 5 {
println!(“The number is greater than 5.”);
} else {
println!(“The number is not greater than 5.”);
}
Example Explanation
- The program evaluates whether number > 5 is true.
- Since number is assigned the value 3, the condition number > 5 evaluates to false.
- Because the condition is false, the else block of the code executes.
- The program prints the message “The number is not greater than 5.” to indicate the outcome of the condition..
3. Else If Statement
What is Else If?
The else if statement extends if to check multiple conditions in sequence. When the initial if condition evaluates to false, the program evaluates the next condition in the else if clause. If none of the conditions match, the final else block (if provided) is executed. This structure ensures that only one branch of code is executed, streamlining complex decision-making processes in programs.
Syntax
if condition1 {
// Code block if condition1 is true
} else if condition2 {
// Code block if condition2 is true
} else {
// Code block if none are true
}
Detailed Explanation
- The else if statement allows multiple conditional checks after the initial if condition fails.
- Each else if clause provides an opportunity to evaluate a new condition.
- If none of the if or else if conditions are met, the else block (if present) is executed.
- This structure ensures all potential scenarios are covered and only one branch of code is executed during runtime.
Example
let number = 7;
if number > 10 {
println!(“The number is greater than 10.”);
} else if number > 5 {
println!(“The number is greater than 5 but not greater than 10.”);
} else {
println!(“The number is 5 or less.”);
}
Example Explanation
The program evaluates the conditions sequentially:
- First, it checks number > 10. Since 7 is not greater than 10, the condition evaluates to false.
- Next, it checks number > 5. This condition evaluates to true, so the corresponding block executes, printing “The number is greater than 5 but not greater than 10.”.
- The else block is skipped because one of the earlier conditions was satisfied.
4. Match Statement
What is Match?
The match statement evaluates a value and matches it against patterns, executing the corresponding code block for the first matching pattern.
Syntax
match value {
pattern1 => { // Code block },
pattern2 => { // Code block },
_ => { // Fallback code block },
}
Detailed Explanation
- Matches a value against multiple patterns.
- Executes the block associated with the first matching pattern.
- Requires exhaustiveness, meaning all possible cases must be covered.
Example
let day = “Monday”;
match day {
“Monday” => println!(“Start of the workweek.”),
“Friday” => println!(“End of the workweek.”),
_ => println!(“Midweek or weekend.”),
}
Example Explanation
The match statement evaluates day:
- The first pattern, “Monday”, matches the value of day. As a result, the block println!(“Start of the workweek.”) executes.
- Other patterns, like “Friday” and _, are ignored because the first match ends the evaluation.
- This ensures efficient execution and simplifies logic.
5. Loop Statement
What is Loop?
The loop construct allows for the creation of a repeating code block that continues indefinitely until an explicit termination condition is met. Within the loop, the break statement can be used to exit and stop the repetition. This makes loop versatile for scenarios where the exit condition is determined dynamically during execution.
Syntax
loop {
// Code block
break; // Terminate loop
}
Detailed Explanation
- Executes the code block repeatedly until explicitly terminated.
- Often used with conditions or to retry operations.
Example
let mut count = 0;
loop {
if count >= 3 {
break;
}
println!(“Count: {}”, count);
count += 1;
}
Example Explanation
The program begins by initializing the variable count to 0. It enters a loop that repeats its execution indefinitely until a termination condition is met. Within the loop, the program performs the following steps:
- It evaluates the current value of count and compares it against the limit of 3.
- If count is less than 3, the program prints the current value of count to the console.
- The value of count is incremented by 1 after each iteration to ensure progress toward the termination condition.
- When count reaches 3, the condition within the loop triggers the break statement, exiting the loop and stopping further iterations.
This approach demonstrates controlled repetition, ensuring the program completes a defined sequence of actions before halting.
6. While Loop
What is While?
A while loop is designed to repeat a block of code as long as the specified condition remains true. Before each iteration, the loop evaluates the condition, and only if it is true does the code block execute. Once the condition becomes false, the loop terminates, ensuring controlled repetition. This construct is particularly useful when the number of iterations cannot be determined in advance, as the loop’s behavior depends entirely on the condition provided.
Syntax
while condition {
// Code block
}
Detailed Explanation
- Continues looping while the condition remains true.
- Ideal for scenarios where the number of iterations is not predetermined.
Example
let mut number = 5;
while number > 0 {
println!(“Number: {}”, number);
number -= 1;
}
Example Explanation
The program evaluates the condition number > 0 at each iteration:
- Prints the current value of number.
- Decreases number by 1.
- Exits the loop when number reaches 0.
7. For Loop
What is For?
A for loop in Rust provides a way to traverse elements in a collection, such as an array or vector, or iterate through a range of values. By automatically assigning each element to a variable during each iteration, it simplifies the process of accessing and processing individual elements sequentially. This construct is especially useful for situations where operations need to be performed on every element within a defined sequence or collection.
Syntax
for item in collection {
// Code block
}
Detailed Explanation
- Automatically iterates over each element in the collection or range.
- Commonly used for iterating over arrays, vectors, and ranges.
Example
for number in 1..=5 {
println!(“Number: {}”, number);
}
Example Explanation
The program iterates over the range 1..=5:
- On each iteration, assigns the next number in the range to number.
- Prints the current value of number.
- Stops after the last number in the range is printed.
Real-Life Project
Project Name: Simple ATM Simulator
Project Goal: Use control flow to implement a menu-driven ATM simulation.
Code for This Project
fn main() {
let balance = 1000;
let mut input = String::new();
println!("Welcome to the ATM");
println!("1. Check Balance\n2. Exit");
std::io::stdin().read_line(&mut input).unwrap();
match input.trim() {
"1" => println!("Your balance is: ${}", balance),
"2" => println!("Thank you for using the ATM."),
_ => println!("Invalid option."),
}
}
Save and Run
- Save the code in a file, for example, main.rs.
- Compile the file using the command rustc main.rs to create an executable.
- Run the generated executable by executing ./main in the terminal.
- This process ensures the Rust program is properly compiled and executed without issues.
Expected Output
Welcome to the ATM
- Check Balance
- Exit
Your balance is: $1000
Insights
- Control flow constructs like if, match, and loops are fundamental for program logic.
- Rust’s syntax ensures clarity and safety in branching and iteration.
- Combining constructs enables powerful, concise logic in programs.
Key Takeaways
- Understand and use Rust’s control flow constructs effectively.
- Test branching logic for correctness in edge cases.
- Leverage pattern matching in match for exhaustive checks.