Module: Control Flow

If Else

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 the number variable is less than 5.
  • println!("Condition was true");: This line is executed only if the condition number < 5 is true.
  • else { ... }: The else block is optional. It provides code to execute if the if condition is false.
  • println!("Condition was false");: This line is executed only if the condition number < 5 is 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 true has its corresponding block of code executed.
  • If none of the if or else if conditions are true, the else block (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 if statement evaluates to either 5 or 6 depending on the value of condition.
  • The result of the if expression is assigned to the number variable.
  • Important: Both branches of the if expression must return values of the same type. In this case, both branches return i32 (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:

  • if and else statements are essential for controlling program flow.
  • if statements can be used as expressions, returning a value.
  • Both branches of an if expression must return values of the same type.
  • Variables declared within if blocks 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.