capypad
0 day streak
rust / beginner
Snippet

Pattern Matching with Match

Rust's match expression is a powerful control flow tool that allows you to compare a value against a series of patterns and execute code based on which pattern matches. It is similar to switch statements in other languages but much more powerful. The underscore _ pattern acts as a catch-all for any value that doesn't match previous patterns.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
fn main() {
let number = 7;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
4..=10 => println!("Between four and ten"),
_ => println!("Something else"),
}
}
Breakdown
1
match number {
Starts a match expression on the number variable
2
1 => println!("One"),
If number equals 1, prints One
3
4..=10 => println!("Between four and ten"),
Range pattern matching numbers 4 through 10
4
_ => println!("Something else"),
Default case that catches all other values