← 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.
Syntax
rust
if condition {
    // body
} else if condition2 {
    // body
} else {
    // body
}

let name = if condition { value1 } else { value2 };

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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `number`, set to `7`
    let number = 7;
    // Check whether `number > 5`
    if number > 5 {
        // Print "Greater than five" to the console (with a trailing newline)
        println!("Greater than five");
    // Otherwise, run this branch
    } else {
        // Print "Five or less" to the console (with a trailing newline)
        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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `grade`, set to `85`
    let grade = 85;
    // Check whether `grade >= 90`
    if grade >= 90 {
        // Print "A" to the console (with a trailing newline)
        println!("A");
    // Otherwise, if `grade >= 80`, run this branch
    } else if grade >= 80 {
        // Print "B" to the console (with a trailing newline)
        println!("B");
    // Otherwise, run this branch
    } else {
        // Print "C or below" to the console (with a trailing newline)
        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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `condition`, set to `true`
    let condition = true;
    // Declare an immutable variable `number`, set to `if condition { 5 } else { 6 }`
    let number = if condition { 5 } else { 6 };
    // Print "number is {}" to the console, substituting in `number` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `count`, set to `3`
    let count = 3;
    // Check whether `count != 0`
    if count != 0 {
        // Print "count is non-zero: {}" to the console, substituting in `count` (with a trailing newline)
        println!("count is non-zero: {}", count);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.