Start learning free

LESSON 73 OF 414 · CONDITIONAL STATEMENTS

If Else in Rust: Choosing Between Two Paths

Lesson Read the full explanation

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

let am_tired = false;
if am_tired {
    println!("I take a nap");
} else {
    println!("I start coding");
}

The code above prints "I start coding" since the expression inside the if evaluates to false and so Rust will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is referred to as an if-else statement.


Assignment
Follow the Coding Tutorial and let's practice with if-else statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS

    If Else in Rust, explained

    What if-else adds

    A plain if does something when a condition is true and nothing otherwise. Often you want a different action in the other case. In plain words: if I'm tired, I take a nap; otherwise, I start coding. Rust writes that with else.

    let am_tired = false;
    if am_tired {
        println!("I take a nap");
    } else {
        println!("I start coding");
    }
    
    I start coding
    

    Here am_tired is false, so Rust skips the first block and runs the one after else. Setting am_tired to true flips the output to I take a nap. Exactly one of the two blocks always runs.

    Rules for else

    • It needs an if. An else can't stand alone. It always belongs to the if just before it.
    • It has no condition. It catches whatever the if didn't: if the condition is false, the else block runs.
    • By convention it sits on the same line as the closing brace. Write } else {. Putting else on the next line compiles, but it is not the standard Rust layout.
    • Its braces are required. As with if, the block always has curly braces, and the condition of the if needs no parentheses.

    Chaining with else if

    When there are more than two outcomes, add else if branches. Rust checks them in order and runs the first one whose condition is true. A final else handles the rest:

    let score = 7;
    if score >= 9 {
        println!("excellent");
    } else if score >= 5 {
        println!("pass");
    } else {
        println!("fail");
    }
    
    pass
    

    Order matters. With a score of 9, both of the first two conditions are true, but only the first block runs, because the chain stops at the first match.

    if-else is an expression

    In Rust, an if-else produces a value, so it can sit on the right side of a let. Both branches must produce the same type, and the final expression of each block has no semicolon:

    let passed = true;
    let message = if passed { "Passed" } else { "Failed" };
    println!("{}", message);
    
    Passed
    

    This replaces the ternary operator found in other languages, which Rust doesn't have. Without an else, the expression form would be a compile error, because the compiler can't give message a value when the condition is false.

    Nesting

    A block can contain any statements, including another if. Nesting is useful when the second decision only matters after the first one:

    let am_tired = false;
    let has_deadline = true;
    if am_tired {
        println!("I take a nap");
    } else {
        if has_deadline {
            println!("I start coding");
        } else {
            println!("I read a book");
        }
    }
    
    I start coding
    

    This particular case is just else if has_deadline, and the flatter version is easier to read. Reach for nesting only when the inner decision really belongs inside one branch.

    The exercise

    The starting code already holds an if:

    let passed: bool = false;
    if passed {
        println!("Passed the test");
    }
    

    With passed set to false, this prints nothing. The step asks you to attach an else branch that prints "Failed the test" with println!. Put else on the same line as the } that closes the if block, then close the new block with its own }:

    let passed: bool = false;
    if passed {
        println!("Passed the test");
    } else {
        println!("Failed the test");
    }
    

    Now the program always reports a result. With false it prints Failed the test.

    Choosing between if and if-else

    Use a plain if when there is nothing to do in the false case, such as printing a warning only when something is wrong. Use if-else when both outcomes need a response, such as reporting a pass or a failure. If you find yourself writing two if statements with opposite conditions, one if-else says the same thing more clearly.

    Common mistakes

    • Writing a condition after else. else passed { ... } is a syntax error. For a second condition use else if.
    • Leaving out the braces. Both blocks need them, even with one statement inside.
    • Adding a semicolon after the closing brace of the if. }; before else ends the statement early and the else then has no if.
    • Branches of different types in an expression. let x = if c { 1 } else { "no" }; doesn't compile.
    • Two separate if statements instead of if-else. Separate ones can both run, or both be skipped, while if-else guarantees exactly one block.

    Key takeaways

    • else runs when the if condition is false, and it never has a condition of its own.
    • Write } else { on one line.
    • Use else if for more than two outcomes. The first true branch wins.
    • An if-else can produce a value, which is how Rust does what a ternary operator does elsewhere.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free