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
ifgives a value;forwalks,whilechecks,looprepeats untilbreak.
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.
What do we know?
We have a list of days late, one per book:
[0, 4, 0, 12]. It is a collection, sofor.
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.
Which numbers does for n in 2..5 visit?
Why does let fee = if late { 50 } else { "none" }; fail?
What happens with let copies = 2; if copies { println!("in stock"); }?
What value does found hold after let found = loop { break 7; };?
Remember
ifis an expression; every branch must give the same type, and the condition must be abool.- Collection or range →
for; condition →while; "until" →loopwithbreak. - Trap:
a..bexcludesb, and numbers are never truthy.
