Sub topic 8
Branching with match
This chapter assumes you can write functions and if/else expressions in Rust. It also assumes you know let bindings and the basic integer and string types.
What match does
A match expression compares one value against a list of patterns. It runs the first arm whose pattern fits and produces that arm's value. Like if, match is an expression, so you can return it from a function or bind it with let.
fn describe(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
x if x % 2 == 0 => "positive even",
_ => "positive odd",
}
}
fn main() {
println!("{}", describe(7));
}This prints positive odd. The example uses three pattern features:
i32::MIN..=-1is a range pattern. It matches every value in the inclusive range.x if x % 2 == 0binds the value tox, then applies a guard. The arm matches only if the guard is true._is the wildcard. It matches anything and binds nothing.
Arms are checked in order
Rust tests arms from top to bottom and stops at the first match. Put specific patterns before general ones. A wildcard placed first would make every later arm unreachable, and the compiler warns you about that.
Exhaustiveness
A match must cover every possible value of the type. If it does not, the program fails to compile with error E0004 ("non-exhaustive patterns"). This is the main reason to prefer match over a chain of if statements. When you add a variant to an enum, the compiler points to every match you need to update.
Matching enums and destructuring
Patterns can pull data out of enum variants and structs. The bindings are available inside the arm.
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Point,
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rect { w, h } => w * h,
Shape::Point => 0.0,
}
}
fn main() {
println!("{}", area(&Shape::Rect { w: 2.0, h: 3.5 }));
println!("{}", area(&Shape::Circle(1.0)));
println!("{}", area(&Shape::Point));
}There is no wildcard here. Every variant is listed, so adding a fourth variant later produces a compile error until you handle it. A wildcard would hide that error. When you match on your own enums, list the variants explicitly where you can.
Because s is a reference, r, w, and h are references to the fields. Rust applies the arithmetic operators to references of numbers, so the expressions still work.
Combining patterns
Two more forms are common:
1 | 2 | 3matches any one of the alternatives.n @ 1..=9binds the matched value tonwhile also checking it against the range.
fn bucket(n: u32) -> String {
match n {
0 => "none".to_string(),
d @ 1..=9 => format!("one digit: {d}"),
10 | 100 | 1000 => "power of ten".to_string(),
_ => "other".to_string(),
}
}
fn main() {
println!("{}", bucket(4));
println!("{}", bucket(100));
}Common errors
- Arms with different types. Every arm must produce the same type, because the
matchis a single expression. Mixing"text"and5is a type error. - Missing cases. A non-exhaustive
matchis a compile error, not a runtime surprise. - A stray binding instead of a constant. A lowercase name in a pattern, such as
limit, creates a new variable that matches anything. It does not compare against an existing variable namedlimit. Use a guard (x if x == limit) for that. - A semicolon after an arm's value. Writing
x => 1;inside the braces is a syntax error. Arms are separated by commas, and a block arm needs no comma.
Exercise
This function fails to compile with E0004. Why, and what is the smallest fix? fn sign(n: i32) -> &'static str { match n { 0 => "zero", x if x > 0 => "positive", x if x < 0 => "negative", } }
Show answer
Arms with guards do not count toward exhaustiveness, so the compiler sees no arm that covers every non-zero value. Replace the last arm with an unguarded one, for example _ => "negative". The earlier arms already handle zero and the positive values, so the remaining values are negative.