Part 01 · Rust Is Not Scary

if, loop, while and for

ifloopwhileforRanges

Making decisions and repeating work, and why if in Rust can give back a value.

⏱ 9 min · Station 8 of 75

The story

A shopkeeper's day is made of two kinds of thinking. Decisions: "if the bill is over a thousand taka, delivery is free; otherwise it's sixty". And repetition: "go through every item in the basket and add up the prices", "keep selling while there's stock left", "keep going until the day's target is reached".

Code needs the same two things. if makes decisions. for, while and loop repeat work. Rust's versions look familiar, with two twists that make them safer: a decision must be a real true or false, and an if can give back a value, like a function.

The idea

if / else if / else chooses one path. The condition must be a bool. And because if is an expression (the same idea as the last line of a function), it can produce a value you store directly:

let delivery = if total >= 100_000 { 0 } else { 6_000 };

Three loops, each for a different kind of repetition:

LoopUse it whenShop example
for x in listyou have a list or a range to go throughadd up every price in the basket
while conditionyou repeat while something stays truesell while stock > 0
loopyou repeat until you decide to stop with breakkeep saving until the target is reached

Ranges are written 1..=3 (1, 2, 3: includes the end) or 1..3 (1, 2: stops before the end).

for price in prices { total += price; }420price = 420, total = 420185price = 185, total = 605150price = 150, total = 75560price = 60, total = 815priceno more items: the loop ends, total = 815
for price in prices visits each item exactly once, in order. Each time round, price is the next item and the running total grows: 420, 605, 755, 815. When the list runs out, the loop ends by itself.

Try it: decisions and loops in the shop

if as a value, and else if for more than two choices:

fn main() {
    let total = 75_500; // ৳755.00 in paisa

    // if is an expression: it gives back a value
    let delivery = if total >= 100_000 { 0 } else { 6_000 };
    println!("delivery: {delivery}");

    let tier = if total >= 200_000 {
        "gold"
    } else if total >= 50_000 {
        "silver"
    } else {
        "regular"
    };
    println!("customer tier: {tier}");
}
delivery: 6000
customer tier: silver

Every branch of the if gives back a value of the same type (here a number, or a piece of text), and the chosen one lands in delivery or tier. No mut variable set in three places, no chance of forgetting one branch.

All three loops in one program:

fn main() {
    // for: go through every item in a list
    let prices = [420, 185, 150, 60];
    let mut total = 0;
    for price in prices {
        total += price;
        println!("added {price:>3}, total {total}");
    }

    // for over a range: 1..=3 means 1, 2, 3
    for day in 1..=3 {
        println!("day {day}");
    }

    // while: repeat as long as a condition is true
    let mut stock = 3;
    while stock > 0 {
        println!("sold one, {stock} were left");
        stock -= 1;
    }

    // loop: repeat until you break, and break can carry a value
    let mut saved = 0;
    let mut days = 0;
    let days_needed = loop {
        saved += 150;
        days += 1;
        if saved >= 1_000 {
            break days;
        }
    };
    println!("saving 150 a day, 1000 takes {days_needed} days");
}
Predict first

Saving 150 taka a day, how many days until the savings reach 1000?

added 420, total 420
added 185, total 605
added 150, total 755
added  60, total 815
day 1
day 2
day 3
sold one, 3 were left
sold one, 2 were left
sold one, 1 were left
saving 150 a day, 1000 takes 7 days

Three things to notice:

  • for price in prices gives you each item in turn. There is no index to manage, so there is no "off by one" mistake and no reading past the end of the list.
  • while checks its condition before each round. When stock reaches 0, the condition is false and the loop is skipped.
  • break days does two things: it stops the loop, and it hands days out as the loop's value, so let days_needed = loop { ... }; works just like let x = if ....

What the compiler says

In Python and JavaScript, if stock: works with a number: 0 counts as false, anything else as true. Rust refuses:

fn main() {
    let stock: u32 = 0;
    if stock {
        println!("in stock");
    }
}
error[E0308]: mismatched types
 --> src/main.rs:3:8
  |
3 |     if stock {
  |        ^^^^^ expected `bool`, found `u32`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `truthy` (bin "truthy") due to 1 previous error

expected `bool`, found `u32` : a condition must be a bool. Say what you mean: if stock > 0. It's two more characters, and nobody reading it has to remember which values count as "false".

Using if as a value comes with two rules, and the compiler explains both. First, every possible path must give a value, so you need an else:

fn main() {
    let total = 75_500;
    let delivery = if total >= 100_000 { 0 };
    println!("{delivery}");
}
error[E0317]: `if` may be missing an `else` clause
 --> src/main.rs:3:20
  |
3 |     let delivery = if total >= 100_000 { 0 };
  |                    ^^^^^^^^^^^^^^^^^^^^^^-^^
  |                    |                     |
  |                    |                     found here
  |                    expected integer, found `()`
  |
  = note: `if` expressions without `else` evaluate to `()`
  = help: consider adding an `else` block that evaluates to the expected type

For more information about this error, try `rustc --explain E0317`.
error: could not compile `noelse` (bin "noelse") due to 1 previous error
  • error[E0317]: `if` may be missing an `else` clause: if total is below 100,000, what is delivery? There's no answer.
  • note: `if` expressions without `else` evaluate to `()` : the missing branch gives back (), nothing, and you can't store nothing in a variable that's supposed to be a number.
  • help: consider adding an `else` block: so add one.

Second, every branch must give the same type:

fn main() {
    let total = 75_500;
    let delivery = if total >= 100_000 { "free" } else { 6_000 };
    println!("{delivery}");
}
error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:3:58
  |
3 |     let delivery = if total >= 100_000 { "free" } else { 6_000 };
  |                                          ------          ^^^^^ expected `&str`, found integer
  |                                          |
  |                                          expected because of this

For more information about this error, try `rustc --explain E0308`.
error: could not compile `mixed` (bin "mixed") due to 1 previous error

expected `&str`, found integer: the first branch gave text, so the compiler decided delivery is text; then the else gave a number. A variable has one type, so pick one: 0 and 6_000, or "free" and "60 taka".

Under the hood

for works through an iterator. for price in prices asks prices for an iterator, a thing that hands out the next item each time and says "done" at the end. That's why there's no index and no way to go past the end. You'll write your own uses of iterators in Iterators; for now, know that a for loop over a list in release mode compiles to the same tight machine code as a hand-written index loop in C.

Ranges are values too. 1..=3 is a real value of type RangeInclusive, and for iterates over it the same way it iterates over a list.

Every if must be complete when it's a value. That rule, plus "every branch, same type", means the compiler can prove a variable like delivery always gets a value. There is no path where it is left empty.

Loops can be named. With nested loops, break stops the innermost one. Give the outer loop a label, 'outer: for ..., and break 'outer; stops that one instead. You won't need it often, but when you do, it saves an extra "found" flag.

Compared with other languages

Why is Rust strict about bool conditions? Here's a real kind of bug. Form fields arrive as text, so a stock of zero arrives as the string "0":

const stockFromForm = "0"; // form fields always arrive as text
if (stockFromForm) {
  console.log("JS: in stock, show the Buy button");
}
const empty = [];
if (empty) {
  console.log("JS: an empty list is truthy too");
}
stock_from_form = "0"  # form fields always arrive as text
if stock_from_form:
    print("Python: in stock, show the Buy button")
JS: in stock, show the Buy button
JS: an empty list is truthy too
Python: in stock, show the Buy button

Both languages decided a stock of "0" means "in stock", because a non-empty string is truthy. JavaScript even treats an empty list as true. The shop shows a Buy button for something it doesn't have. In Rust that code doesn't compile: you'd have to parse "0" into a number first, then write stock > 0, and the bug never happens.

PythonJavaScriptGoRust
Conditionanything (truthy)anything (truthy)bool onlybool only
if gives a valuea if c else bc ? a : bnoyes, if c { a } else { b }
Loopsfor, whilefor, for..of, whileonly forfor, while, loop
Loop gives a valuenononobreak value in loop

Key takeaway

if conditions must be a real bool, so write stock > 0, not stock. if is an expression: it can give back a value, as long as there's an else and every branch has the same type. Use for to go through lists and ranges (1..=3 includes 3, 1..3 doesn't), while to repeat while something is true, and loop with break to repeat until you decide to stop, optionally handing a value out with break value.

Practice

Objective: combine a for loop, if as a value, and a counter.

Challenge: go through the prices [420, 185, 150, 999, 60]. Label each one premium (400 or more) or regular, count how many are premium, and add up the total. At the end, delivery is free (0) if the total is at least 1000, otherwise 60.

Expected result:

 420  premium
 185  regular
 150  regular
 999  premium
  60  regular
2 premium items, total 1814, delivery 0
Hint 1

You need two mut counters before the loop: total and premium.

Hint 2

Inside the loop, let label = if price >= 400 { "premium" } else { "regular" }; gives you the text in one line.

Hint 3

{price:>4} right-aligns the price in 4 characters so the labels line up.

Solution
fn main() {
    let prices = [420, 185, 150, 999, 60];
    let mut total = 0;
    let mut premium = 0;

    for price in prices {
        let label = if price >= 400 { "premium" } else { "regular" };
        if price >= 400 {
            premium += 1;
        }
        total += price;
        println!("{price:>4}  {label}");
    }

    let delivery = if total >= 1_000 { 0 } else { 60 };
    println!("{premium} premium items, total {total}, delivery {delivery}");
}

The program checks price >= 400 twice. That's fine for now; once you know Pattern Matching with match, you'll see neater ways to get the label and the count from one decision.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →