Deciding and repeating
Every language needs a way to choose between actions and a way to repeat them. Rust's tools for this will look familiar: if, while, for. Two things set Rust apart, and both make programs shorter and safer.
First, almost everything is an expression. An if produces a value, a loop can hand a value back when it stops, and a match is usually written on the right-hand side of a let. You rarely need a mutable variable whose only job is to be filled in by one of several branches.
Second, Rust has patterns: a small language for describing the shape of a value ("a pair whose first element is zero", "a list with at least two items", "a number between 90 and 100") and pulling pieces out of it at the same time. Patterns appear in match, in let, in function parameters and in for loops, and the compiler checks that a match covers every possible case. That check catches a whole class of bug, the forgotten case, at compile time. Experienced Rust programmers reach for match the way Python programmers reach for if.
Branches and loops
fn main() {
// `if` is an expression: both branches must have the same type.
let rainfall_mm = 42;
let advice = if rainfall_mm > 30 {
"take an umbrella"
} else {
"leave it at home"
};
println!("{rainfall_mm} mm: {advice}");
// `loop` repeats until `break`, and `break` can carry a value out.
let mut power = 1;
let first_over_1000 = loop {
power *= 2;
if power > 1000 {
break power;
}
};
println!("first power of two over 1000: {first_over_1000}");
// `while` checks a condition before each pass.
let mut n = 27;
let mut steps = 0;
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
steps += 1;
}
println!("27 reaches 1 after {steps} Collatz steps");
// `for` walks any iterator; ranges are the simplest.
for i in 1..4 {
print!("{i} ");
}
println!("| exclusive");
for i in (1..=10).rev().step_by(3) {
print!("{i} ");
}
println!("| inclusive, reversed, every third");
// Labels let `break` and `continue` reach an outer loop.
let grid = [[3, 8, 1], [9, 4, 7], [2, 6, 5]];
'search: for (r, row) in grid.iter().enumerate() {
for (c, &value) in row.iter().enumerate() {
if value == 7 {
println!("found 7 at row {r}, column {c}");
break 'search;
}
}
}
}42 mm: take an umbrella
first power of two over 1000: 1024
27 reaches 1 after 111 Collatz steps
1 2 3 | exclusive
10 7 4 1 | inclusive, reversed, every third
found 7 at row 1, column 2Some details that trip up newcomers:
- The condition of an
iforwhilemust be abool. There is no "truthiness":if countis an error whencountis a number; writeif count != 0. No parentheses are needed around the condition, and braces around the body are always required. - When
ifis used as a value, every branch must produce the same type, and anifwithoutelsehas type(). That rule prevents a variable that is "sometimes a string and sometimes nothing". loopis the honest way to write an infinite loop; the compiler even warns if you writewhile true. Because the compiler knows aloopcan only end throughbreak, it can use the value ofbreak poweras the value of the whole loop.a..bis a half-open range (includesa, excludesb), anda..=bincludes both ends. Ranges are iterators, so you can chain adaptors like.rev()and.step_by(3)onto them; lesson 7 covers iterators properly.forloops over anything iterable. In the grid search,.iter().enumerate()yields pairs of an index and a reference to each row, and the pattern(c, &value)takes each pair apart and copies the number out of its reference. This is the idiomatic replacement for C'sfor (i = 0; i < n; i++): you almost never index manually in Rust.- A label like
'search(an apostrophe and a name) letsbreakorcontinueact on an outer loop, so you don't need a flag variable to escape nested loops.
Patterns and match
Definition— pattern
A pattern describes the shape of a value. It can be a literal (3, 'x', "hi"), a range (1..=9), a variable name that binds whatever is there, the wildcard _ that matches anything without binding it, or a structure built from these (tuples, arrays, slices, structs, enum variants). Patterns can be combined with | ("or") and given a name with @.
Definition— match
match value { pattern => expression, ... } compares value against each arm's pattern from top to bottom and evaluates the expression of the first arm that matches. An arm may add a guard, pattern if condition, which must also be true. A match must be exhaustive: its patterns together must cover every possible value of the type, or the program does not compile.
fn describe(c: char) -> &'static str {
match c {
'a' | 'e' | 'i' | 'o' | 'u' => "a lowercase vowel",
'a'..='z' => "a lowercase consonant",
'A'..='Z' => "an uppercase letter",
'0'..='9' => "an ASCII digit",
' ' | '\t' | '\n' => "whitespace",
c if c.is_alphabetic() => "a letter outside ASCII",
_ => "something else",
}
}
fn grade(score: u32) -> String {
match score {
90..=100 => String::from("A"),
75..=89 => String::from("B"),
n @ 50..=74 => format!("C ({} points short of a B)", 75 - n),
0..=49 => String::from("not yet"),
_ => format!("{score} is not a valid score"),
}
}
fn main() {
for c in ['e', 'k', 'Q', '7', ' ', 'ñ', '?'] {
println!("{c:?} is {}", describe(c));
}
for s in [97, 80, 61, 12, 140] {
println!("{s}: {}", grade(s));
}
}'e' is a lowercase vowel
'k' is a lowercase consonant
'Q' is an uppercase letter
'7' is an ASCII digit
' ' is whitespace
'ñ' is a letter outside ASCII
'?' is something else
97: A
80: B
61: C (14 points short of a B)
12: not yet
140: 140 is not a valid scoreRead describe from top to bottom, the way the computer does. 'e' matches the first arm. 'k' fails the first arm and matches the range 'a'..='z'; the vowels are also in that range, but they never get there because the first matching arm wins. 'ñ' is not in any ASCII range, so it reaches the arm c if c.is_alphabetic(), which binds the character to c and then checks the guard. Everything else falls to _. (The return type &'static str is the type of a string literal, text baked into the program; lesson 4 explains the notation.)
In grade, n @ 50..=74 both tests that the score is in the range and binds it to n for use in the arm. The last arm catches anything above 100.
Exhaustiveness
Take away the catch-all arm from a match on a number and the compiler will not let it through. Here is a match on a u8 that forgot about values above 9:
let level: u8 = 3;
let label = match level {
0 => "off",
1..=5 => "low",
6..=9 => "high",
};error[E0004]: non-exhaustive patterns: `10_u8..=u8::MAX` not covered
--> ne.rs:3:23
|
3 | let label = match level {
| ^^^^^ pattern `10_u8..=u8::MAX` not covered
|
= note: the matched value is of type `u8`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shownThe compiler worked out exactly which values are missing. This becomes even more valuable with enums (lesson 5): add a new variant to an enum, and every match that does not handle it becomes a compile error pointing at the code you need to update.
Destructuring, if let, let else and while let
Patterns are not only for match. Every let takes a pattern (let (x, y) = point; is one), and three shorter forms cover the common case where you care about just one shape:
if let PATTERN = value { ... } else { ... }runs the block only if the pattern matches.let PATTERN = value else { ... };(let-else) binds the pattern's variables for the rest of the function, or runs theelseblock, which must leave:return,break,continueor a panic.while let PATTERN = value { ... }loops as long as the pattern keeps matching.
The program below also uses slice patterns, which match lists by their length and ends, and Option, the type of a value that may be absent: Some(v) holds a value, None holds nothing. (split_once returns Some((before, after)) if the separator is present and None if not.) Lesson 5 covers Option in depth.
fn summarize(readings: &[i32]) -> String {
match readings {
[] => String::from("no readings"),
[only] => format!("one reading: {only}"),
[first, second] => format!("two readings: {first} then {second}"),
[first, .., last] => format!("{} readings, from {first} to {last}", readings.len()),
}
}
fn parse_setting(line: &str) -> Option<(String, u32)> {
// let-else: bind the pattern or leave the function.
let Some((key, value)) = line.split_once('=') else {
return None;
};
let Ok(number) = value.trim().parse::<u32>() else {
return None;
};
Some((key.trim().to_string(), number))
}
fn main() {
println!("{}", summarize(&[]));
println!("{}", summarize(&[18]));
println!("{}", summarize(&[18, 21]));
println!("{}", summarize(&[18, 21, 19, 25]));
for line in ["volume = 7", "brightness=80", "theme: dark", "width = wide"] {
// if-let: run a block only when the pattern matches.
if let Some((key, n)) = parse_setting(line) {
println!("set {key} to {n}");
} else {
println!("could not read {line:?}");
}
}
// while-let: loop as long as the pattern matches.
let mut stack = vec!["plates", "bowls", "cups"];
while let Some(top) = stack.pop() {
println!("took the {top}");
}
let (x, y, z) = (1, 2, 3);
let [a, b, c] = [10, 20, 30];
println!("{}", x + y + z + a + b + c);
}no readings
one reading: 18
two readings: 18 then 21
4 readings, from 18 to 25
set volume to 7
set brightness to 80
could not read "theme: dark"
could not read "width = wide"
took the cups
took the bowls
took the plates
66The slice patterns in summarize are checked for exhaustiveness too: [], [only], [first, second] and [first, .., last] (two or more, with .. standing for "any number in between") cover every possible length. The match reads like a specification of the function.
parse_setting shows the shape that let-else was designed for: validate, or leave early. Each let ... else peels off one failure case and keeps the happy path flat at the left margin, instead of nesting one if let inside another. If you forget to leave in the else block, the compiler says the else clause "does not diverge" and suggests return or panic!.
while let Some(top) = stack.pop() is the standard way to drain a stack or a work queue: pop returns Some(item) until the vector is empty and then None, which ends the loop.
Let chains
Sometimes you need several patterns and ordinary conditions to all hold before doing something. Since Rust 1.88 (mid-2025), code in the 2024 edition can join let patterns and boolean conditions with && in an if or while; this is called a let chain. Each later part can use the variables bound by earlier parts.
fn main() {
let entries = ["Amaka:34", "Tomás:", "Mei:29", "Priya:abc", "Oleksandr:41"];
for entry in entries {
// A let chain (Rust 1.88+, edition 2024): patterns and conditions joined by &&.
if let Some((name, age_text)) = entry.split_once(':')
&& let Ok(age) = age_text.parse::<u32>()
&& age >= 30
{
println!("{name} ({age}) may join the over-30s league");
} else {
println!("skipping {entry:?}");
}
}
let is_weekend = |day: &str| matches!(day, "Saturday" | "Sunday");
println!("{} {}", is_weekend("Sunday"), is_weekend("Monday"));
}Amaka (34) may join the over-30s league
skipping "Tomás:"
skipping "Mei:29"
skipping "Priya:abc"
Oleksandr (41) may join the over-30s league
true falseBefore let chains, the same logic needed three nested ifs or a helper function. The layout with each && on its own line and the opening brace on a line by itself is how the official formatter, rustfmt, lays out long chains.
The last two lines show matches!, a macro that asks "does this value match this pattern?" and returns a bool; it is handy inside filters and assertions. (The |day: &str| ... syntax is a closure, a small unnamed function; lesson 7 covers closures.) Rust 1.95 added a related feature, if let guards on match arms, which lets a guard try a pattern too; you will see it in newer codebases.
Choosing the right tool
With this many forms, how do professionals choose? A rough guide:
| Situation | Reach for |
|---|---|
| Several distinct cases, each with its own action | match |
One interesting case, and "otherwise do nothing" (or a short else) | if let |
| A value must have a certain shape or the function cannot continue | let ... else |
| Several patterns and conditions that must all hold | a let chain |
| Repeat until a pattern stops matching (draining a queue) | while let |
| Only need a yes/no answer about the shape | matches! |
Two habits matter more than the table. Prefer early exits to deep nesting: a function that checks its inputs with let-else and then does its real work at the left margin is easier to read than a staircase of braces. And be careful with _: a wildcard arm makes a match exhaustive by fiat, which means that when someone later adds a new case to an enum, the compiler will not tell you about the places that should handle it. When matching on your own enums, many teams list every variant explicitly for exactly this reason.
What match costs
A fair question from anyone who has written C: is all this pattern machinery slow? It isn't. A match is compiled, not interpreted. The compiler turns the arms into a decision tree: it tests each part of the value at most as often as needed and branches straight to the right arm. For a match on a small integer or a character with many literal arms, the optimiser (LLVM) will often build a jump table, an array of addresses indexed by the value, so choosing an arm takes the same few instructions however many arms there are. Ranges become a pair of comparisons. Slice patterns compile to a check of the slice's length followed by direct loads of the elements they bind.
Exhaustiveness checking costs nothing at run time at all: it happens entirely in the compiler. The same is true of the guarantee that a binding like n in n @ 50..=74 has the right type. This is the meaning of the phrase zero-cost abstraction, which you will meet again and again in Rust: a high-level construct that compiles to the code you would have written by hand, so that clarity and speed are not in competition.
There is one cost worth knowing. Guards (if condition on an arm) are ordinary code, run in order, so a long chain of guarded arms is a chain of ifs. That is rarely a problem, but if you find yourself writing ten guards, it may be a sign that the data deserves a better type, such as an enum, which is where lesson 5 begins.
Example— From nested ifs to one match
Suppose a thermostat must decide what to do from two readings: whether a window is open, and the temperature in whole degrees. A first draft might nest ifs: if the window is open, turn the heating off; otherwise, if it is below 18, heat; otherwise, if it is above 26, cool; otherwise, idle. Written as a match on the pair (window_open, temperature), the arms are (true, _) => Off, (false, ..=17) => Heat, (false, 27..) => Cool and (false, _) => Idle. Each arm states one complete situation, the compiler checks that no situation is missing, and the order of the arms shows the priority (an open window overrides everything) at a glance. Readers who never saw the nested draft can still check the logic against the specification line by line.
Common misconceptions
Misconception
"1..10 includes 10." It doesn't: a..b stops before b. Write 1..=10 for an inclusive range. A useful memory aid: 0..v.len() covers exactly the valid indexes of v.
Misconception
"The best-fitting arm of a match wins." The first matching arm wins, so specific arms must come before general ones. If an earlier arm already covers everything a later arm could match, the compiler warns that the later pattern is unreachable.
Misconception
"I need an index variable to loop over an array." Index loops (for i in 0..v.len()) work, but each v[i] may cost a bounds check and the style invites off-by-one errors. Iterate over the elements directly (for x in &v), use .enumerate() when you also need the position, and .zip() to walk two sequences together.
Misconception
"The variable in a pattern compares against an existing variable." In match x { limit => ... }, limit is a new binding that matches anything, even if a variable called limit exists outside. To compare against a variable, use a guard: n if n == limit => .... Named constants (const LIMIT: u32 = 10;) are the exception: they can be used as patterns.
Exercises
1. Control flow and pattern matching
Warm-upComputationalWhat does this program print?
fn main() {
let mut x = 1;
let r = loop {
x *= 3;
if x > 50 {
break x - 1;
}
};
println!("{r}");
}
2. Control flow and pattern matching
CoreComputationalWhat does this program print? Write the four words separated by spaces.
fn main() {
for n in [0, 7, 12, 15] {
let s = match n {
0 => "zero",
n if n % 15 == 0 => "fifteen",
n if n % 3 == 0 => "three",
_ => "other",
};
println!("{s}");
}
}
3. Control flow and pattern matching
CoreComputationalWhat does this program print?
fn main() {
let mut count = 0;
'outer: for i in 1..=4 {
for j in 1..=4 {
if j > i {
continue 'outer;
}
count += 1;
}
}
println!("{count}");
}
4. Control flow and pattern matching
Warm-upComputationalWhich numbers does for i in (1..=10).rev().step_by(4) visit, in order?
5. Control flow and pattern matching
CoreComputationalWhat does this print?
fn main() {
let product = match [4, 5, 6, 7].as_slice() {
[a, .., b] => a * b,
_ => 0,
};
println!("{product}");
}
6. Control flow and pattern matching
StretchComputationalWhy does this not compile?
fn first_word(s: &str) -> &str {
let Some(w) = s.split_whitespace().next() else {
println!("empty");
};
w
}
Further reading and resources
- The Rust Programming Language, section 3.5: Control Flow · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The Rust Programming Language, chapter 19: Patterns and Matching · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The Rust Reference: PatternsEvery kind of pattern, precisely, including the rules for bindings and slice patterns.
- The Rust Edition GuideWhere let chains and other 2024-edition changes are described.