</>
Skip to content
Rust lessons (12/43)

Rust — If Else

The basics — familiar but stricter

let temperature = 31;

if temperature > 28 {
    println!("It's hot");
} else if temperature > 18 {
    println!("Pleasant");
} else {
    println!("Bring a jacket");
}

Two hard rules:

  1. The condition must be a real bool — no truthy integers/strings
  2. Braces are mandatory, even for single statements
if temperature > 28
    println!("hot");     // ❌ compile error — braces required

if IS an expression — the big idea

In most languages if is a statement. In Rust it produces a value:

let number = 7;

let label = if number % 2 == 0 { "even" } else { "odd" };
println!("{}", label);      // "odd"

No ternary operator exists because if already works as one.

Rules when capturing values:

  • Every branch must yield the same type
  • Branch bodies end WITHOUT semicolons (so the expression is the branch's value)
  • Missing else + assigning = error (what would the value be otherwise?)
// ❌ type mismatch — i32 vs ()
let x = if flag { 5 };           // no else!

// ✓ both branches produce i32:
let x = if flag { 5 } else { 0 };

let … if inside larger expressions

let price = 100;
let discount_rate = if premium { 0.2 } else { 0.05 };

let final_price = price * (1.0 - discount_rate);

Combining conditions

if age >= 13 && age <= 19 { … }        // range check
if day == "Sat" || day == "Sun" { … }
if !(name.is_empty()) { … }

// Rust's elegant inclusive range syntax for matching comes later;
// for plain conditions, explicit && stays idiomatic.

Nested vs guard-style

// nested pyramid:
if user.exists() {
    if user.active {
        grant();
    }
}

// flatter with early structure in functions:
if !user.exists() || !user.active { return; }
grant();

Same logic; the second reads top-down and scales better.

Gotchas: = instead of == won't even compile (no silent assignment) · conditions need bools, so if count errors helpfully · forgetting that unbraced single lines are illegal.

Mini Practice

  1. Grade classifier returning letter via if-expression.
  2. FizzBuzz for 1–15 using % and branches.
  3. Convert three nested ifs into guard-style returns.
  4. Capture a max of two numbers: let max = if a > b { a } else { b };
  5. Trigger each of the three gotchas once, on purpose.

Next: match →

Related Topics

Frequently Asked Questions about If Else

What is If Else in Rust?

If Else is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn If Else?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.

Why is If Else important in Rust?

If Else is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.