Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 132 ยท Operators and Control Flow

if, else if and else

Learn Rust if expressions - conditions must be bool, getting values out of branches, else if chains, if let, let chains in the 2024 edition, early return and why Rust has no ternary operator.

Almost every program needs to make decisions: show an error if the input is empty, charge a fee if the balance is low, stop if a limit is reached. In Rust you decide with if. It looks like if in other languages, but with two differences that matter: the condition must be a real bool, and if is an expression, which means it produces a value you can store in a variable or return from a function.

This lesson covers the basic form, else if chains, using if as an expression (Rust's replacement for the ternary operator), if let for pattern matching, the 2024-edition let chains that combine both, and early returns. Multi-way decisions on one value are usually better written with match, the topic of the next lesson.

The basic if

An if has a condition without parentheses and a block in braces. The braces are required, even for a single statement:

Rust if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The condition temperature > 25 is a comparison that produces a bool. Parentheses around it are allowed but unneeded; rustc even warns about them, and rustfmt removes them. Leaving out the braces is a syntax error, which prevents the famous "goto fail" style bug where a second indented line looks like part of the if but is not.

Conditions must be bool

Rust does not convert numbers, strings or Options to booleans. There is no "truthiness". If you want "the list is not empty", you must write it:

Rust A number is not a condition (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler says error[E0308]: mismatched types, with the label expected `bool`, found integer. Write what you mean: if items > 0, if !list.is_empty(), if name.len() > 3. The strictness is a feature, because in C-like languages if (x = 5) or if (count) often hide bugs.

else if chains

To test several conditions in order, chain else if. The first condition that is true wins, and the rest are skipped:

Rust Grading with else if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because the chain stops at the first match, the order of the tests matters: the check score >= 80 is only reached when score >= 90 was false, so you do not have to write score >= 80 && score < 90. If the chain gets long, or compares one value with many constants, switch to match.

if is an expression

Here is the idea that sets Rust apart from C and Java. An if / else is an expression that evaluates to the value of whichever block runs. Each block's value is its last expression, without a semicolon:

Rust Getting a value out of if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is Rust's answer to the ternary operator condition ? a : b: there is no such operator, because if condition { a } else { b } does the same job and reads clearly. You can use it anywhere an expression fits, including inside function arguments and println!.

Two rules keep this safe:

  1. Every branch must have the same type. The compiler has to know the type of price at compile time, so if cond { 1 } else { "one" } is an error.
  2. An if that produces a value must have an else. Without else, nothing would be left for the false case.
Rust Branches with different types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0308]: `if` and `else` have incompatible types, pointing at the two branches with expected integer, found `&str` . To fix it, make both branches produce the same type, for example "1" and "one", or 1 and 0.

An if without else is allowed only when its block has type (), the unit type: it can only do things (print, assign, return), not produce a value.

Rust if without else needs a unit block (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0317]: `if` may be missing an `else` clause, with the label expected integer, found `()` . Add else { ... } with a value of the same type.

A stray semicolon changes the meaning

Because the last expression without a semicolon is the value, adding a semicolon turns it into a statement and the block's value becomes ():

Rust Semicolon turns a value into nothing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get error[E0308]: mismatched types (twice, once per branch), expected `&str`, found `()` , with the hint remove this semicolon to return this value. This is the same rule you saw with function bodies, and it is the single most common reason an if expression fails to compile.

Early return

if is also how you leave a function early. A guard clause at the top handles the unusual case and returns immediately, so the rest of the function stays flat and readable instead of nested inside else blocks:

Rust Guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The return keyword ends the function at once with the given value. Its type is ! (never, see type aliases and the never type), which is why a branch that returns fits next to branches that produce other types. When the function ends with an expression, you omit return and the semicolon.

if let

Often the condition is "does this value have this shape?" For an Option, you want to run code only when it is Some, and use the value inside. if let combines the check and the unpacking:

Rust if let with Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

if let PATTERN = EXPRESSION { ... } evaluates the expression and tests whether the pattern matches. If it does, the names in the pattern are bound inside the block. The optional else runs otherwise. It is a shorter way to write a match where you care about one case. When you need to handle several variants, use match. Patterns are covered in patterns in depth.

if let works with enums, tuples, ranges and more:

Rust if let with enums and refutable patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You can mix else if and else if let in one chain, as the loop shows.

Let chains (Rust 2024, 1.88)

Real conditions often need both a pattern and a boolean test: "if the value is Some, and it is large enough". Before Rust 1.88 you had to nest the ifs. With the 2024 edition you can join let conditions and ordinary boolean tests with && in a single if (or while). This is called a let chain.

Rust Let chains with &&

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A let chain evaluates left to right and stops at the first part that fails (like &&). Names bound by an earlier let are available to later parts and inside the block, as points is here. Let chains are only available in edition 2024 (our editor uses it); in older editions the compiler rejects && after a let. Without let chains, you needed nested statements or a match with a guard:

Rust
// The older way: nesting
if let Ok(n) = text.parse::<i32>() {
    if n % 2 == 0 {
        return Some(n);
    }
}

One limit to remember: you cannot use || to join let conditions.

let ... else for early exits

A close relative is let ... else, which unpacks a pattern or diverges (returns, breaks, continues or panics) when it does not match. It keeps the success path unindented:

Rust let else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

let ... else is covered in patterns in depth. The else block must end in something of type !, such as return, which is why it compiles.

Common mistakes and style

  • Comparing to true: write if ready, not if ready == true.
  • Redundant else after return: if the if block returns, the code after it is the else case. Skip the else.
  • Long else if ladders on one value: use match, which also checks that you covered every case.
  • Using if to build a bool: if a > b { true } else { false } is just a > b.
  • Assignment instead of comparison: if x = 5 is a compile error in Rust, since = is not an expression of type bool.

When you want a value that depends on a condition, prefer a single let value = if ... { ... } else { ... }; over declaring let mut value; and assigning it in each branch. The expression form keeps the variable immutable, and the compiler checks that every branch produces a value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which condition compiles in Rust?

    Conditions must be of type bool. count != 0 is a bool, while integers and strings are never converted to bool automatically.
  2. 2. What does this print?

    let n = if 4 > 5 { 1 } else if 4 > 3 { 2 } else { 3 }; println!("{n}");

    The first condition is false, the second (4 > 3) is true, so the value of that branch, 2, is the value of the whole if expression.
  3. 3. Why does let x = if flag { 1 }; fail to compile?

    Without else, the false case would produce () instead of an integer. The compiler reports E0317 and asks for an else clause.
  4. 4. What is the Rust equivalent of the ternary operator cond ? a : b?

    if is an expression, so if cond { a } else { b } produces a value and replaces the ternary operator.
  5. 5. What does if let Some(n) = opt && n > 10 { ... } need to compile?

    Combining a let pattern with a boolean test using && is a let chain, available in the 2024 edition.

Summary

  • if condition { ... } else { ... }: no parentheses needed, braces required, and the condition must be a bool.
  • Chain tests with else if; the first true condition runs and the rest are skipped.
  • if is an expression: let x = if c { a } else { b }; replaces the ternary operator. All branches must have the same type, and the else is required when a value is produced.
  • A trailing semicolon inside a branch turns its value into ().
  • Use guard clauses with return to keep the main path flat.
  • if let PATTERN = value runs a block only when the pattern matches; let chains (edition 2024) combine let patterns and boolean tests with &&.
  • For many cases on one value, prefer match.

Next: match Expressions