Start learning free

LESSON 72 OF 414 · CONDITIONAL STATEMENTS

If Statements in Rust: Making Decisions

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    let is_rainy: bool = true;
    if is_rainy {
        println!("I bring an umbrella");
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast

If I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if conditions {
    // instructions
}

The keyword if tells Rust to execute the code inside the curly braces (where we have our Rust comment) only if the conditions written between if and the opening curly brace are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

let is_rainy: bool = true;
if is_rainy {
    println!("I bring an umbrella");
}

The code above prints "I bring an umbrella" since the condition is_rainy evaluates to true

But this code:

let am_hungry: bool = false;
if am_hungry {
    println!("I have breakfast");
}

prints nothing since am_hungry evaluates to false.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS

    If Statements in Rust, explained

    Why programs need decisions

    Programs rarely do the same thing every time. They check a situation and act on it: show an error only if something went wrong, give a discount only if the customer qualifies. The if statement is how Rust code does this. It runs a block of code only when a condition is true.

    let is_rainy: bool = true;
    if is_rainy {
        println!("I bring an umbrella");
    }
    
    I bring an umbrella
    

    The syntax

    An if has three parts: the keyword, a condition, and a block in curly braces.

    if condition {
        // statements that run when the condition is true
    }
    

    Rust differs from several other languages in two ways here:

    • No parentheses around the condition. Write if is_rainy {, not if (is_rainy) {. Parentheses are allowed, but the compiler warns that they are unnecessary.
    • The braces are always required. Even a one-line body needs them. There is no braceless form like if x println!(...).

    Boolean conditions

    The condition must be a bool, which is either true or false. If it is true, the block runs. If it is false, the block is skipped and the program continues after the closing brace.

    let am_hungry: bool = false;
    if am_hungry {
        println!("I have breakfast");
    }
    

    This prints nothing, since am_hungry is false.

    Rust is strict about this. It never converts other types to a boolean, so a number or a string can't stand in for a condition:

    let n = 5;
    if n {
        println!("x");
    }
    
    error[E0308]: mismatched types
      expected `bool`, found integer
    

    To test a number, compare it: if n != 0 { ... }. The comparison produces a bool.

    Using a bool directly

    When a variable already holds a bool, the variable alone is the condition. Writing if passed == true works but is redundant. Write if passed, and use if !passed for the opposite.

    Several decisions in one program

    The three decisions from everyday life become three independent if statements. Each one is checked on its own:

    let is_rainy = true;
    let am_hungry = false;
    let am_tired = true;
    
    if is_rainy {
        println!("I bring an umbrella");
    }
    if am_hungry {
        println!("I have breakfast");
    }
    if am_tired {
        println!("I take a nap");
    }
    
    I bring an umbrella
    I take a nap
    

    Any number of them can run, including none.

    Variables inside a block

    The braces of an if also form a scope. A variable declared inside the block exists only until the closing brace:

    let passed = true;
    if passed {
        let message = "well done";
        println!("{}", message);
    }
    // message no longer exists here
    

    Using message after the block is a compile error. Variables declared before the if, like passed, can be read inside the block, so a block can use everything declared around it.

    The conditions of real programs usually come from comparisons and combinations of them, which the next lessons cover. The structure never changes: a bool expression, then a block.

    The exercise

    The starting code declares let passed: bool = true;. The lesson builds the decision in three steps:

    1. Write an if whose condition is passed, and open the block with {.
    2. Inside the block, print "Passed the test" with println!.
    3. Add an else block that prints "Failed". The else has no condition of its own. It runs exactly when the if condition was false.
    let passed: bool = true;
    if passed {
        println!("Passed the test");
    } else {
        println!("Failed");
    }
    

    With passed set to true, this prints Passed the test. Change the value to false and it prints Failed. Exactly one of the two blocks runs, whichever way the condition goes. Writing } else { on one line is the usual Rust layout: it closes the first block and opens the second.

    Reading the result

    After an if finishes, the program carries on with the next line, whether the block ran or not. An if never stops the program; it only decides whether one block takes part in it. That is why the third example above can print nothing and still leave the rest of the program running normally.

    Common mistakes

    • Forgetting the braces. They are mandatory, so the compiler rejects an if without them.
    • Using = instead of ==. = assigns and == compares. In Rust, if x = 5 is a compile error rather than a silent bug.
    • Using a non-bool condition. Integers, strings and Option values need an explicit comparison or check first.
    • Putting else on its own line after the brace. The code compiles in Rust, but the style convention is } else {.
    • Adding a condition to else. else never takes one. For a second condition, use else if.

    Key takeaways

    • if condition { ... } runs the block only when the condition is true.
    • The condition must be a bool, and it needs no parentheses.
    • Curly braces are always required.
    • An else block covers every case the if did not.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free