7 / 35

Rust Basics· 14 min read· Lesson 7 of 35

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:

src/main.rs
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.");
}
}
Output
Come on in, we're open!
Running low on milk, time to reorder.
  1. if is followed by a condition, an expression that produces a bool.
  2. hour >= 7 && hour < 17 uses comparison operators (>= “at least”, < “less than”) joined with && (“and”). Both parts must be true.
  3. If the condition is true, the first block runs. Otherwise the else block runs.
  4. The second if has no else. 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:

Output
error[E0308]: mismatched types
--> src/main.rs:3:8
|
3 | if cups_left {
| ^^^^^^^^^ expected `bool`, found integer

Say 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:

src/main.rs
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.");
}
}
Output
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:

src/main.rs
fn main() {
let size = 'L';
let price = if size == 'L' { 500 } else { 450 };
println!("Latte size {size}: {price} cents");
}
Output
Latte size L: 500 cents
  1. If size is 'L', the if produces 500. Otherwise it produces 450.
  2. Each block’s last expression has no semicolon, so it becomes the value of the block.
  3. That value is stored in price. Note the semicolon at the very end, which finishes the let.

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:

src/main.rs
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");
}
Output
Made cup number 1
Made cup number 2
Made cup number 3
Order complete: 3 cups
  1. Each pass through the loop body is called an iteration. Each iteration adds 1 to cups_made and prints it.
  2. When cups_made reaches 3, break stops the loop.
  3. break cups_made also hands back a value, so the loop produces 3, which goes into total_cups. Like if, loop is 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:

src/main.rs
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.");
}
Output
Pulling a shot. Beans left: 50g
Pulling a shot. Beans left: 32g
Out of beans! Only 14g left.
  1. A double espresso uses 18 grams of beans. While we have at least 18g, we pull a shot and subtract 18.
  2. After two shots, beans_grams is 14. The condition 14 >= 18 is 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:

src/main.rs
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");
}
Output
Item: 300 cents
Item: 450 cents
Item: 325 cents
Total: 1075 cents
  1. for price in order_prices runs the block once per item. Each time, price holds the current item.
  2. 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).

src/main.rs
fn main() {
for table in 1..=3 {
println!("Wiping table {table}");
}
for seconds in (1..4).rev() {
println!("Espresso ready in {seconds}...");
}
println!("Ding!");
}
Output
Wiping table 1
Wiping table 2
Wiping table 3
Espresso ready in 3...
Espresso ready in 2...
Espresso ready in 1...
Ding!
  1. 1..=3 includes 3, so all three tables get wiped.
  2. (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.

src/main.rs
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");
}
Output
A latte costs 450 cents
  1. match drink looks at the value of drink.
  2. Each line inside is an arm: a pattern, then =>, then the value (or code) for that case.
  3. "espresso" | "muffin" matches either one (both cost 300 cents). | means “or” in patterns.
  4. _ is a catch-all that matches anything else.
  5. Like if, match is an expression, so the matching arm’s value goes into price.

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
src/main.rs
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:

Output
Cup 1
Cup 2
Cup 3
Cup 4
Cup 5 + free cookie!
Cup 6
Cup 7
Cup 8
Cup 9
Cup 10 + free cookie!
3 cups: medium order

The _ 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 / else choose which code runs. Conditions must be bool.
  • if is an expression, so let price = if ... { 500 } else { 450 }; works, as long as both branches have the same type.
  • loop repeats until break (which can return a value), while repeats while a condition is true, and for goes through each item.
  • Ranges: 1..4 is 1–3, and 1..=4 is 1–4. .rev() counts backwards.
  • match picks 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

Search lessons

Type to search all lessons.