Skip to the workspace
Pebellslearn by building
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.

rust / Control Flow: if, loop, while and for

Explore each scene at your own pace.

01 · The rule

The rule

Control Flow: if, loop, while and for

In 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.

Trace branch values and repeated work through their stopping conditions.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.