Rust Programming: Control Flow - If Else
Rust's if and else statements provide a way to execute different blocks of code based on whether a condition is true or false. They are fundamental to controlling the flow of your program.
1. Basic if Statement
The simplest form of an if statement executes a block of code only if a condition is true.
fn main() {
let number = 7;
if number < 5 {
println!("Condition was true");
} else {
println!("Condition was false");
}
}
Explanation:
if number < 5 { ... }: This checks if the value of thenumbervariable is less than 5.println!("Condition was true");: This line is executed only if the conditionnumber < 5is true.else { ... }: Theelseblock is optional. It provides code to execute if theifcondition is false.println!("Condition was false");: This line is executed only if the conditionnumber < 5is false.
Output:
Condition was false
2. if Statements Without Curly Braces
If the block of code to be executed contains only a single expression, you can omit the curly braces {}. However, this is generally discouraged for readability, especially as code grows more complex.
fn main() {
let number = 7;
if number < 5 {
println!("Condition was true"); // No curly braces
} else {
println!("Condition was false");
}
}
This produces the same output as the previous example.
3. else if Chains
You can chain multiple if and else if conditions together to check for different scenarios.
fn main() {
let number = 5;
if number < 5 {
println!("Condition was less than 5");
} else if number > 5 {
println!("Condition was greater than 5");
} else {
println!("Condition was equal to 5");
}
}
Explanation:
- The conditions are evaluated in order.
- The first condition that evaluates to
truehas its corresponding block of code executed. - If none of the
iforelse ifconditions are true, theelseblock (if present) is executed.
Output:
Condition was equal to 5
4. if Expressions
In Rust, if statements are expressions. This means they evaluate to a value. This is a powerful feature that allows you to use if statements directly in variable assignments or as part of other expressions.
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
Explanation:
- The
ifstatement evaluates to either5or6depending on the value ofcondition. - The result of the
ifexpression is assigned to thenumbervariable. - Important: Both branches of the
ifexpression must return values of the same type. In this case, both branches returni32(an integer).
Output:
The value of number is: 5
5. Scope of Variables in if Blocks
Variables declared within an if block (or else block) are scoped to that block. This means they are only accessible within the block where they are defined.
fn main() {
let number = 7;
if number < 5 {
let message = "Condition was true";
println!("{}", message);
} else {
println!("Condition was false");
}
// println!("{}", message); // This would cause a compile error!
}
The message variable is only valid within the if block. Trying to access it outside of that block will result in a compile-time error.
Key Takeaways:
ifandelsestatements are essential for controlling program flow.ifstatements can be used as expressions, returning a value.- Both branches of an
ifexpression must return values of the same type. - Variables declared within
ifblocks are scoped to those blocks. - Use curly braces
{}for clarity, even if the block contains only one statement. This improves readability and maintainability.
This covers the basics of if and else statements in Rust. Understanding these concepts is crucial for writing more complex and dynamic programs.