capypad
0 day streak
rust / intermediate
Snippet

Pattern Destructuring in Match Arms

Match arms can destructure complex enum variants directly, binding their inner fields to variables. This eliminates the need for manual field access after matching. The destructuring works recursively, allowing deep extraction of nested data structures within a single pattern.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[derive(Debug)]
enum Device {
Mobile { brand: String, model: String },
Desktop { cores: u8, ram_gb: u32 },
}
 
fn main() {
let device = Device::Mobile { brand: String::from("Apple"), model: String::from("iPhone") };
match device {
Device::Mobile { brand, model } => println!("Mobile: {} {}", brand, model),
Device::Desktop { cores, ram_gb } => println!("Desktop: {} cores, {} GB RAM", cores, ram_gb),
}
}
Breakdown
1
#[derive(Debug)]
Derive Debug trait to enable {:?} formatting for the enum
2
enum Device { Mobile {...}, Desktop {...} }
Enum with two variants containing different payload types
3
Device::Mobile { brand, model } =>
Destructures the struct-like variant, extracting brand and model as local variables
4
println!("Mobile: {} {}", brand, model)
Uses the destructured variables directly without any field access syntax