capypad
0 day streak
rust / beginner
Snippet

if let - Concise Pattern Matching

if let provides a concise way to handle single pattern matches without the exhaustive requirements of match. It extracts values from enum variants. while let continues looping while a pattern matches, useful for iterators and streams.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
enum Color {
Red,
Blue,
Green,
Custom(u8, u8, u8),
}
 
fn main() {
let preferred = Color::Custom(100, 50, 150);
if let Color::Custom(r, g, b) = preferred {
println!("Custom RGB: {}, {}, {}", r, g, b);
} else {
println!("Standard color");
}
while let Color::Blue = Color::Blue {
println!("Blue detected!");
break;
}
}
Breakdown
1
enum Color { Red, Blue, Green, Custom(u8, u8, u8) }
Enum with unit variants and tuple variant Custom
2
if let Color::Custom(r, g, b) = preferred {
Binds fields from matching variant
3
while let Color::Blue = Color::Blue {
Loop continues as long as pattern matches