[Avg. reading time: 5 minutes]
Match
match is Rust’s pattern matching construct. Superficially it looks like switch, but semantically it is stricter and more powerful.
Exhaustive by default, all possible cases must be handled.
Pattern based, not just value based. An expression, so it can return a value
fn main() { let number = 34; println!("Tell me about {number}"); match number { 1 => println!("One"), 2 | 3 | 5 | 7 | 11 => println!("This is a prime"), 13..=19 => println!("A teen"), matched @ 10..=100 => { println!("Found {matched} between 10 and 100"); } _ => println!("Not special"), } }
- | matches multiple values
- ..= matches inclusive ranges
- @ binds the matched value
- _ is the catch-all and is mandatory
if all cases are not explicitly covered
fn main() { let boolean = true; let binary = match boolean { false => 0, true => 1, }; println!("{boolean} -> {binary}"); }
- Every arm (section) must return the same type.
Tuples with Match
fn main() { let triple = (0, -2, 3); println!("Tell me about {:?}", triple); // Match can be used to destructure a tuple match triple { // Destructure the second and third elements (0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z), (1, ..) => println!("First is `1` and the rest doesn't matter"), (.., 2) => println!("last is `2` and the rest doesn't matter"), (3, .., 4) => println!("First is `3`, last is `4`, and the rest doesn't matter"), // `..` can be used to ignore the rest of the tuple _ => println!("It doesn't matter what they are"), // `_` means don't bind the value to a variable } }