Conditionals (if-else & match)

🦀 Rust Lesson 6 Beginner

Conditionals control the branch paths of execution based on boolean checks. In Rust, conditionals are expressions that can return values directly, and match blocks enforce exhaustive evaluations.

1 If Expressions and Match Exhaustiveness

Rust conditionals provide two key features:

  • If Expressions: Since `if` is an expression, it returns a value. This allows you to assign the result of an if statement directly to a variable: `let result = if active { 1 } else { 0 };`. Both branches must return the same data type.
  • Exhaustive Match Pattern: The `match` keyword acts like switch-case statements, but **requires all possible cases to be handled**. The compiler will throw an error if any pattern is left unhandled. The placeholder pattern `_` acts as the default fallback case.
2 Conditional Codes

Let's run a program evaluating if-expressions and exhaustive match blocks:

Rust — Conditionals ▶ Run Code
fn main() {
    let score = 85;

    // If as an expression
    let grade = if score >= 90 {
        "A"
    } else if score >= 80 {
        "B"
    } else {
        "F"
    };
    println!("Grade: {}", grade);

    // Exhaustive Match statement
    let dice_roll = 3;
    match dice_roll {
        1 => println!("Rolled 1!"),
        3 => println!("Rolled 3!"),
        _ => println!("Rolled something else!"), // default placeholder pattern
    }
}
3 Code Challenge
Challenge: Write a match statement evaluating a character representing ratings ('A', 'B', 'C'). Print descriptive feedback for each character. Ensure you include the default pattern placeholder `_` to satisfy compile exhaustiveness checks.