Sub topic 3
Branching with match
match compares one value against a list of patterns and runs the code for the first pattern that fits. This chapter covers how match works: its syntax, how it evaluates, and the rules that follow from it being an expression. It assumes you can read basic Rust, know how enums with data are declared, and understand moves and references at a basic level. The next chapter covers what the compiler checks about the list of arms. Later chapters cover the full range of pattern syntax.
The shape of a match
A match has a scrutinee (the value being examined) and a list of arms. Each arm is a pattern, a =>, and an expression.
#[derive(Debug, Clone, Copy)]
enum Direction {
North,
East,
South,
West,
}
fn turn_right(d: Direction) -> Direction {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
fn main() {
let mut d = Direction::North;
for _ in 0..5 {
println!("{:?}", d);
d = turn_right(d);
}
}Each pattern here is a variant path. Arms are separated by commas. The comma is optional after an arm whose body is a { ... } block, but most code keeps it for uniformity.
The function body is only the match, with no return and no trailing semicolon. That works because match is an expression, as the next sections show.
How evaluation works
Rust evaluates the scrutinee once. It then tests the arms from top to bottom and runs the first arm whose pattern fits. It never looks at later arms. The value of that arm's expression becomes the value of the whole match.
Because the first fit wins, arm order matters whenever patterns overlap. A broad pattern placed above a narrow one hides the narrow one.
fn fizz(n: u32) -> String {
match (n % 3, n % 5) {
(0, 0) => String::from("FizzBuzz"),
(0, _) => String::from("Fizz"),
(_, 0) => String::from("Buzz"),
_ => n.to_string(),
}
}
fn main() {
for n in [15, 9, 10, 7] {
println!("{n}: {}", fizz(n));
}
}This code prints FizzBuzz, Fizz, Buzz, and 7. The arm (0, _) also fits 15, but (0, 0) comes first and takes it. Put specific patterns first and general ones last.
The _ pattern fits any value and discards it. It is the usual catch-all arm. Here it also keeps the match complete, which the next chapter explains.
Match is an expression
Since match produces a value, you can bind it, return it, or pass it to a function.
fn main() {
let hour = 14;
let greeting = match hour {
0..=11 => "good morning",
12..=17 => "good afternoon",
_ => "good evening",
};
println!("{greeting}");
}Two rules follow from this.
- Every arm must produce the same type. If one arm yields
&strand another yieldsi32, the compiler reports a mismatched types error pointing at the offending arm. - When you use the result,
let x = match ... { ... };needs the final semicolon, as anyletstatement does. Whenmatchis the last expression in a function, you leave the semicolon off.
If every arm ends with a semicolon-terminated statement, each arm produces (). This is the normal style for a match run only for its side effects, such as printing.
Arms that carry data
A pattern can reach inside a variant and bind its fields to new names. Those names are valid only inside that arm.
enum Command {
Quit,
Move { x: i32, y: i32 },
Say(String),
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::Quit => String::from("quit"),
Command::Move { x, y } => format!("move to ({x}, {y})"),
Command::Say(text) => {
let n = text.len();
format!("say {text:?} ({n} bytes)")
}
}
}
fn main() {
let commands = [
Command::Quit,
Command::Move { x: 3, y: -1 },
Command::Say(String::from("hi")),
];
for cmd in &commands {
println!("{}", describe(cmd));
}
}The three variants show the three pattern shapes. A unit variant such as Command::Quit needs nothing extra. A struct-like variant uses braces: Command::Move { x, y } binds the fields x and y. A tuple variant uses parentheses: Command::Say(text) binds the single field to text.
The Say arm uses a block body. A block is an expression, so its last line, without a semicolon, is the arm's value. Use a block when the arm needs local let bindings or several steps.
Here cmd is a &Command, so x, y, and text become references into the original value. Nothing is moved or copied out. A later chapter covers this rule in detail, including how to match by value instead.
Arms that do not return a value
Some arm expressions never produce a value because they leave the current code path. return, break, continue, and panic! have the special type ! (never), which fits any expected type. This lets one arm continue normally while another exits early.
fn double(s: &str) -> i32 {
let n: i32 = match s.parse() {
Ok(n) => n,
Err(_) => return -1,
};
n * 2
}
fn main() {
println!("{}", double("21"));
println!("{}", double("oops"));
}The Ok arm has type i32. The Err arm returns from the function, so it needs no i32 of its own. The same shape works with continue inside a loop. The chapters on Result and let else build on this pattern.
Matching other types
match is not limited to enums. Any value whose type has patterns can be matched: integers, char, bool, tuples, references, strings, and slices. Matching on a &str compares against string literals.
fn http_reason(code: u16) -> &'static str {
match code {
200 => "OK",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown",
}
}
fn is_yes(answer: &str) -> bool {
match answer {
"y" | "yes" => true,
_ => false,
}
}
fn main() {
println!("{}", http_reason(404));
println!("{}", is_yes("yes"));
}You cannot match a String directly against a literal, because a String is not a &str. Call .as_str() first: match name.as_str() { ... }.
Common mistakes
- A variable name where you meant a constant. A bare lowercase name in a pattern is a new binding that matches everything. It does not compare against a variable that is already in scope. For example,
match n { limit => ... }always runs the first arm and shadowslimit. To compare against a fixed value, use a literal, aconst, or a guard. Guards are covered in a later chapter. - A catch-all arm too early.
_ => ...or a bare binding above other arms makes those arms unreachable. The compiler warns about this, so read warnings frommatchcarefully. - Using
matchfor one case. When only one pattern matters and everything else is ignored, a four-linematchwith_ => {}is noise. Theif letform, covered in a later chapter, is the usual replacement. - Arms of different types. If one arm is
Stringand another is&str, convert one so both agree, for example with.to_string().
Exercise
In a match on a u32 with the arms _ => "other", 0 => "zero", 1..=9 => "digit" in that order, which arm runs for the input 5, and what does the compiler tell you about the other arms?
Show answer
The first arm, _ => "other", runs, because _ fits every value and the first fitting arm wins. The compiler warns that the 0 and 1..=9 arms are unreachable. Moving _ to the end fixes both the behavior and the warning.
Exercise
What does this function return for label(true, true) and for label(false, true)? fn label(a: bool, b: bool) -> &'static str { match (a, b) { (true, _) => "first", (_, true) => "second", _ => "neither" } }
Show answer
label(true, true) returns "first", because (true, _) is the first arm that fits. label(false, true) returns "second", because (true, _) does not fit and (_, true) does.