Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Introduction to Rust  ›  Lesson

Control Flow: if, loop, while and for

Control Flow and Constructs 12 minIn Rust, if is an expression that produces a value, and loop, while and for repeat code, with for being the usual way to walk through a collection or range.

Control Flow: if, loop, while and for

The library program makes decisions (is this book overdue?) and repeats work (go through every book on the shelf). Rust has one way to decide and three ways to repeat, and one twist that makes them neater than in many languages.

The rule

if gives a value; for walks, while checks, loop repeats until break.

if is an expression. It can sit on the right of let, as long as every branch gives the same type. The condition must be a real bool; Rust never treats a number as true or false.

let days_late = 4;
let fee = if days_late > 0 { days_late * 10 } else { 0 };

No parentheses around the condition, braces always required.

for walks a range or collection. This is the everyday loop.

let titles = ["The Salt Road", "Night Garden", "Iron Tides"];
for title in titles {
    println!("{title}");
}
for day in 1..=3 {
    println!("day {day}"); // 1, 2, 3
}

1..4 stops before 4; 1..=4 includes it.

while repeats as long as a condition holds.

let mut copies = 3;
while copies > 0 {
    copies -= 1;
}

loop repeats forever until break, and break can carry a value out:

let mut tries = 0;
let found = loop {
    tries += 1;
    if tries == 3 { break tries * 100; }
};

continue skips to the next pass of any loop.

The shortcut

Match the loop to what you know before starting: a collection or range → for; a condition → while; nothing, just "until" → loop.

Counting overdue booksStep 1 of 4
  1. What do we know?

    We have a list of days late, one per book: [0, 4, 0, 12]. It is a collection, so for.

The trap is writing if count { ... } with an integer as in C or Python. Rust refuses to compile it: write if count > 0.

Drills

Answer fast — trust the rule.

quick drill

Which numbers does for n in 2..5 visit?

quick drill

Why does let fee = if late { 50 } else { "none" }; fail?

quick drill

What happens with let copies = 2; if copies { println!("in stock"); }?

quick drill

What value does found hold after let found = loop { break 7; };?

Remember

  • if is an expression; every branch must give the same type, and the condition must be a bool.
  • Collection or range → for; condition → while; "until" → loop with break.
  • Trap: a..b excludes b, and numbers are never truthy.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPick the loop

The library program must (a) print every title in a list, (b) keep asking for a card number until a valid one arrives, and (c) set a late fee to 0 or 50 depending on whether a book is overdue. Explain which construct fits each and why.