← Back to Rust Course | Chapter 3: Control Flow | Lesson 1 of 7

if/else Expressions

if and else let your program pick a different path depending on whether something is true or false.

Basic if/else

An if expression evaluates a boolean condition and runs the associated block only when it is true; an optional else block runs otherwise. No parentheses are needed around the condition, unlike C or Java.

Example: Basic if/else

markup
fn main() {
    let number = 7;
    if number > 5 {
        println!("Greater than five");
    } else {
        println!("Five or less");
    }
}

else if Chains

Multiple conditions can be chained with else if, checked in order from top to bottom. The first matching branch runs, and the rest are skipped.

Example: else if Chains

markup
fn main() {
    let grade = 85;
    if grade >= 90 {
        println!("A");
    } else if grade >= 80 {
        println!("B");
    } else {
        println!("C or below");
    }
}

if as an Expression

Because if is an expression, not just a statement, it can produce a value directly, which you can assign to a variable. Both branches must return values of the same type.

Note: Notice there are no semicolons after 5 and 6 -- they are the tail expressions of each block.

Example: if as an Expression

markup
fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };
    println!("number is {}", number);
}

Condition Must Be a Bool

Rust requires the if condition to be an actual bool value; it will not implicitly treat a nonzero integer as true, unlike C. This prevents an entire category of bugs from mistyped conditions.

Example: Condition Must Be a Bool

markup
fn main() {
    let count = 3;
    if count != 0 {
        println!("count is non-zero: {}", count);
    }
}
Common Mistakes
  1. Wrapping the condition in parentheses like if (x > 5), which is unnecessary and unidiomatic in Rust.
  2. Forgetting that if is an expression and can return a value, then writing overly verbose code with extra let mut variables.
  3. Mixing types between the if and else branches when using if as an expression, which fails to compile.
Chapter Summary
  • if/else if/else branch on boolean conditions; no parentheses are required around the condition.
  • if is an expression in Rust, so it can produce a value that is assigned directly to a variable.
  • All branches of an if used as an expression must evaluate to the same type.
  • The condition must be a bool -- Rust does not implicitly convert numbers to booleans.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.