Control Flow
Part 1 · Rust. Make decisions with if and else, repeat work with loop, while and for, count with ranges, and get a first taste of match.
So far our programs run straight from top to bottom, like a barista who makes exactly one drink and then goes home. Real programs need to decide (“Is the café open?”) and repeat (“Make a drink for every order in the queue”). That’s called control flow: controlling which lines run, and how many times. This lesson covers if, three kinds of loops, ranges, and a first look at match.
Making decisions with if
An if runs some code only when a condition is true:
fn main() { let hour = 9; let milk_litres = 2;
if hour >= 7 && hour < 17 { println!("Come on in, we're open!"); } else { println!("Sorry, we're closed."); }
if milk_litres < 3 { println!("Running low on milk, time to reorder."); }}Come on in, we're open!Running low on milk, time to reorder.ifis followed by a condition, an expression that produces abool.hour >= 7 && hour < 17uses comparison operators (>=“at least”,<“less than”) joined with&&(“and”). Both parts must be true.- If the condition is true, the first block runs. Otherwise the
elseblock runs. - The second
ifhas noelse. If milk isn’t low, nothing happens.
The comparison operators are == (equal), != (not equal), <, >, <= and >=. To combine conditions, use && (and), || (or) and ! (not).
Warning
In Rust, the condition must be a bool. Some languages treat 0 as false and other numbers as true, but Rust doesn’t. Writing if cups_left { where cups_left is a number gives:
error[E0308]: mismatched types --> src/main.rs:3:8 |3 | if cups_left { | ^^^^^^^^^ expected `bool`, found integerSay what you mean instead: if cups_left > 0 {.
Several choices with else if
When there are more than two possibilities, chain them with else if:
fn main() { let cups_ordered = 12;
if cups_ordered == 0 { println!("Nothing ordered yet."); } else if cups_ordered <= 5 { println!("A normal order."); } else if cups_ordered <= 10 { println!("A big order! Grab a tray."); } else { println!("That's a catering order. Call the manager."); }}That's a catering order. Call the manager.Rust checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest. 12 isn’t 0, isn’t ≤ 5, isn’t ≤ 10, so we land in the final else.
if is an expression
Remember from Functions that expressions produce values? if is one! That means you can use it on the right side of let:
fn main() { let size = 'L'; let price = if size == 'L' { 500 } else { 450 }; println!("Latte size {size}: {price} cents");}Latte size L: 500 cents- If
sizeis'L', theifproduces500. Otherwise it produces450. - Each block’s last expression has no semicolon, so it becomes the value of the block.
- That value is stored in
price. Note the semicolon at the very end, which finishes thelet.
Both branches must produce the same type. If one gives a number and the other gives text, Rust complains: `if` and `else` have incompatible types. A variable can only have one type, so both answers must fit the same container.
Repeating with loop
loop repeats its block forever, until you tell it to stop with break:
fn main() { let mut cups_made = 0;
let total_cups = loop { cups_made += 1; println!("Made cup number {cups_made}");
if cups_made == 3 { break cups_made; } };
println!("Order complete: {total_cups} cups");}Made cup number 1Made cup number 2Made cup number 3Order complete: 3 cups- Each pass through the loop body is called an iteration. Each iteration adds 1 to
cups_madeand prints it. - When
cups_madereaches 3,breakstops the loop. break cups_madealso hands back a value, so the loop produces3, which goes intototal_cups. Likeif,loopis an expression.
Tip
If you ever write a loop that never stops (an infinite loop), your program will keep running. Press Ctrl + C in the terminal to stop it. Everyone does this at least once!
Repeating with while
while repeats as long as a condition stays true. It checks the condition before every iteration:
fn main() { let mut beans_grams = 50;
while beans_grams >= 18 { println!("Pulling a shot. Beans left: {beans_grams}g"); beans_grams -= 18; }
println!("Out of beans! Only {beans_grams}g left.");}Pulling a shot. Beans left: 50gPulling a shot. Beans left: 32gOut of beans! Only 14g left.- A double espresso uses 18 grams of beans. While we have at least 18g, we pull a shot and subtract 18.
- After two shots,
beans_gramsis 14. The condition14 >= 18is false, so the loop ends.
Use while when you don’t know in advance how many times you’ll repeat, only when to stop.
Looping over things with for
Most of the time you want to do something for each item in a collection. That’s for:
fn main() { let order_prices: [u32; 3] = [300, 450, 325]; let mut total = 0;
for price in order_prices { println!("Item: {price} cents"); total += price; }
println!("Total: {total} cents");}Item: 300 centsItem: 450 centsItem: 325 centsTotal: 1075 centsfor price in order_pricesruns the block once per item. Each time,priceholds the current item.- We add each price to
total. After the loop, we have the sum.
for is the safest and most common loop in Rust. You can’t accidentally read past the end of the array, because the loop stops by itself after the last item.
Ranges: counting with for
A range is a sequence of numbers. 1..4 means 1, 2, 3 (it stops before 4). 1..=4 means 1, 2, 3, 4 (the = includes the end).
fn main() { for table in 1..=3 { println!("Wiping table {table}"); }
for seconds in (1..4).rev() { println!("Espresso ready in {seconds}..."); } println!("Ding!");}Wiping table 1Wiping table 2Wiping table 3Espresso ready in 3...Espresso ready in 2...Espresso ready in 1...Ding!1..=3includes 3, so all three tables get wiped.(1..4)is 1, 2, 3, and.rev()reverses it, giving a countdown.
Note
a..b leaving out b feels odd at first, but it fits nicely with indexes starting at 0. 0..3 gives exactly 0, 1, 2, the three valid positions in a three-item array.
A first taste of match
match compares a value against a list of patterns and runs the code for the first one that fits. Think of a coin-sorting machine: each coin drops into the slot that matches its size.
fn main() { let drink = "latte";
let price = match drink { "espresso" | "muffin" => 300, "cappuccino" => 425, "latte" => 450, "mocha" => 475, _ => 0, };
println!("A {drink} costs {price} cents");}A latte costs 450 centsmatch drinklooks at the value ofdrink.- Each line inside is an arm: a pattern, then
=>, then the value (or code) for that case. "espresso" | "muffin"matches either one (both cost 300 cents).|means “or” in patterns._is a catch-all that matches anything else.- Like
if,matchis an expression, so the matching arm’s value goes intoprice.
Rust insists that a match covers every possible value. Here, drink could be any text at all, so the _ arm is required. Leave it out and the compiler refuses, because some drink would have no price. That might sound strict, but it means you can never forget a case. You’ll use match constantly once we meet enums in Enums and Match.
Try it yourself
The café gives a free cookie with every 5th coffee. Write a program that loops over cup numbers 1 to 10 (inclusive) and prints Cup N for each, adding + free cookie! when the number divides evenly by 5. Then use match on a cups: u32 value of 3 to print "small order" for 1–2 cups, "medium order" for 3–5, and "large order" for anything else.
Hint: n % 5 == 0 is true when n divides evenly by 5. In match, a range pattern looks like 1..=2.
Show solution
fn main() { for cup in 1..=10 { if cup % 5 == 0 { println!("Cup {cup} + free cookie!"); } else { println!("Cup {cup}"); } }
let cups: u32 = 3; let label = match cups { 1..=2 => "small order", 3..=5 => "medium order", _ => "large order", }; println!("{cups} cups: {label}");}Output:
Cup 1Cup 2Cup 3Cup 4Cup 5 + free cookie!Cup 6Cup 7Cup 8Cup 9Cup 10 + free cookie!3 cups: medium orderThe _ arm also catches 0. A real till might treat zero cups as “empty order”, which you could add as its own 0 => arm.
Recap
if/else if/elsechoose which code runs. Conditions must bebool.ifis an expression, solet price = if ... { 500 } else { 450 };works, as long as both branches have the same type.looprepeats untilbreak(which can return a value),whilerepeats while a condition is true, andforgoes through each item.- Ranges:
1..4is 1–3, and1..=4is 1–4..rev()counts backwards. matchpicks the first matching arm, must cover every case, and_catches everything else.
What’s next
You’ve finished Rust Basics! 🎉 Next, we’ll learn the idea that makes Rust special: how it manages memory without a garbage collector. Start the next module with Ownership.
0 of 35 lessons complete