Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

if

Goal of This Episode

Use if to let a program decide whether to do something based on a condition.

Main Text

So far, our programs have run from top to bottom, one line at a time. But real programs need to make “judgments” — if such-and-such, then do something.

That’s what if is for.

Basic Usage

fn main() {
    let x = 7;
    if x > 3 {
        println!("Greater than 3");
    }
}

The logic is simple: x is 7. Is 7 greater than 3? Yes, so the code inside the curly braces {} runs.

What If the Condition Doesn’t Hold?

Try changing x to 1:

fn main() {
    let x = 1;
    if x > 3 {
        println!("Greater than 3");
    }
}

Run it and… nothing. Because 1 is not greater than 3, the condition is false, so the code inside the curly braces gets skipped.

Recap

  • if is followed by a condition; if the condition is true, the code inside the curly braces runs.
  • If the condition is false, the whole block is skipped.
  • Rust’s if conditions don’t need parentheses around them.