rust / intermediate
Snippet
Pattern Matching with Match Expressions
Match expressions in Rust provide powerful pattern matching capabilities. You can match on enum variants, include guard clauses with 'if' conditions, and destructure complex data directly within the pattern. The compiler ensures exhaustiveness checking, meaning all possible cases must be handled or the code won't compile. This makes pattern matching both expressive and safe.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#[derive(Debug)]enum Color {RGB(u8, u8, u8),Hex(String),Named(String),}fn describe_color(color: &Color) -> String {match color {Color::RGB(r, g, b) if r == g && g == b => {format!("Grayscale: r={}, g={}, b={}", r, g, b)}Color::RGB(r, g, b) => format!("RGB: #{:02x}{:02x}{:02x}", r, g, b),Color::Hex(code) if code.starts_with('#') => format!("Hex color: {}", code),Color::Hex(code) => format!("Invalid hex: {}", code),Color::Named(name) => format!("Named color: {}", name),}}fn main() {let colors = vec![Color::RGB(255, 0, 0),Color::RGB(128, 128, 128),Color::Hex(String::from("#00FF00")),Color::Named(String::from("azure")),];for c in &colors {println!("{:?}: {}", c, describe_color(c));}}
Breakdown
1
#[derive(Debug)]
Derive macro to implement Debug trait for printable enum representation
2
enum Color { RGB(u8, u8, u8), ... }
Enum definition with tuple variants holding RGB values and string variants
3
match color { ... }
Match expression evaluating the color enum value
4
Color::RGB(r, g, b) if r == g && g == b =>
Pattern with guard clause: matches gray colors where all channels equal
5
Color::Hex(code) if code.starts_with('#') =>
Guard clause checking string content after destructuring
6
format!("...", r, g, b)
Macro formatting RGB values as hexadecimal color code