Control Flow and Pattern Matching
Exhaustive match, destructuring, slice patterns, if let and let else.
match must cover every case, and it binds values as it tests them.
if is an expression
if produces a value, so there is no ternary operator:
fn main() {
let cond = true;
let x = if cond { 1 } else { 2 };
println!("x = {x}");
let grade = if x > 5 { "high" } else if x > 0 { "low" } else { "zero" };
println!("grade = {grade}");
}while and for
while tests each pass; for walks a range or a collection:
fn main() {
let mut n = 0;
while n < 3 {
n += 1;
}
println!("while ran to {n}");
for i in 0..3 {
println!("range {i}");
}
for i in (0..3).rev() {
println!("rev {i}");
}
let nums = [10, 20, 30];
for v in nums {
println!("array {v}");
}
}0..3 excludes 3; 0..=3 includes it. continue skips to the next pass:
fn main() {
let mut total = 0;
for n in 0..10 {
if n % 2 == 0 {
continue;
}
total += n;
}
println!("odd sum {total}");
}There is no C-style for (i = 0; ...): a range covers counting, for covers the rest.
loop with a value
loop repeats until you break, and break can carry a value out:
fn main() {
let mut count = 0;
let found = loop {
count += 1;
if count == 4 {
break count * 10;
}
};
println!("loop returned {found}");
}Labelled breaks
A label lets break leave an outer loop:
fn main() {
let mut hits = 0;
'outer: for a in 0..5 {
for b in 0..5 {
if a * b > 6 {
println!("stopping at {a}*{b}");
break 'outer;
}
hits += 1;
}
}
println!("inner ran {hits} times");
}Labels start with ' and work with continue too.
match basics
Each arm is a pattern, and the first match wins:
fn main() {
let n = 3;
let label = match n {
1 => "one",
2 | 3 => "two or three",
4..=6 => "four to six",
_ => "many",
};
println!("{label}");
let c = 'k';
let kind = match c {
'a' | 'e' | 'i' | 'o' | 'u' => "vowel",
'a'..='z' => "consonant",
_ => "other",
};
println!("{kind}");
}| is “or”, ..= an inclusive range, _ anything.
match is an expression, but it works as a statement too — drop the binding and the
semicolon, and each arm just does something:
fn main() {
let n = 3;
let label = match n {
1 => "one",
2 | 3 => "two or three",
_ => "many",
};
println!("as an expression: {label}");
match n {
1 => println!("as a statement: one"),
2 | 3 => {
let doubled = n * 2;
println!("as a statement: two or three, doubled {doubled}");
}
_ => println!("as a statement: many"),
}
}Non-exhaustive is an error
Miss a case and the compiler names exactly what you missed:
fn main() {
let n: u8 = 3;
let label = match n {
1 => "one",
2 => "two",
};
println!("{label}");
}Guards and bindings
A guard is an if on an arm. @ binds the value you matched:
fn main() {
let n = 5;
let msg = match n {
x if x < 0 => "negative",
0 => "zero",
x @ 1..=9 => {
println!(" bound x = {x}");
"single digit"
}
_ => "big",
};
println!("{msg}");
}Destructuring
A pattern takes a value apart, and names the pieces:
fn main() {
let pair = (0, 7);
let where_at = match pair {
(0, 0) => "origin",
(0, y) => {
println!(" y = {y}");
"on the y axis"
}
(x, 0) => {
println!(" x = {x}");
"on the x axis"
}
_ => "somewhere else",
};
println!("{where_at}");
}The same syntax works in a let, as chapter 2 did with tuples.
Slice patterns
An array can be matched by shape, with .. for “the rest”:
fn main() {
let nums = [1, 2, 3, 4, 5];
let [first, .., last] = nums;
println!("first {first} last {last}");
let [a, b, rest @ ..] = nums;
println!("a {a} b {b} rest {rest:?}");
}In a match, the arms cover the possible shapes:
fn main() {
let pair = [10, 20];
let desc = match pair {
[0, 0] => "both zero",
[_, 0] => "second zero",
[0, _] => "first zero",
[_, _] => "neither zero",
};
println!("{desc}");
}if let
When only one pattern interests you, if let replaces a match with a _ arm:
fn main() {
let point = (0, 7);
if let (0, y) = point {
println!("on the y axis at {y}");
}
}It takes an else too.
let else
let else binds or leaves. The else block must diverge — return, break or panic:
fn main() {
let text = "42";
let Ok(n) = text.parse::<i32>() else {
println!("not a number");
return;
};
println!("parsed {n}");
}Ok is the success half of Result — chapter 2’s parse, covered in chapter 8.
let chains
Two fallible patterns in one condition, both bound:
fn main() {
let a = "6";
let b = "7";
if let Ok(x) = a.parse::<i32>() && let Ok(y) = b.parse::<i32>() {
println!("product {}", x * y);
}
let c = "nope";
if let Ok(x) = a.parse::<i32>() && let Ok(y) = c.parse::<i32>() {
println!("never prints {x} {y}");
} else {
println!("one side failed");
}
}if let guards
A plain guard tests. An if let guard tests and binds:
fn main() {
let text = "200";
let plain = match text.parse::<i32>() {
Ok(n) if n > 100 => "over a hundred",
Ok(_) => "small",
Err(_) => "not a number",
};
println!("{plain}");
}That guard only answers yes or no. This one binds a second value while testing it:
fn main() {
let rows = [("6", "7"), ("200", "x"), ("nope", "1")];
for (a, b) in rows {
let desc = match a.parse::<i32>() {
Ok(x) if let Ok(y) = b.parse::<i32>() => {
println!(" {x} * {y} = {}", x * y);
"both parsed"
}
Ok(_) => "second is not a number",
Err(_) => "first is not a number",
};
println!("{a:>5} {b:>4} -> {desc}");
}
}matches!
A macro that answers a pattern question with a bool:
fn main() {
let n = 5;
println!("in 1..=9: {}", matches!(n, 1..=9));
println!("odd: {}", matches!(n, x if x % 2 == 1));
let c = 'k';
println!("lowercase: {}", matches!(c, 'a'..='z'));
}Use it where you want a condition, not a branch. Chapter 20 tests shapes with
assert!(matches!(..)).