Patterns pop up in a number of places in Rust, and here are all the examples
match
Armsmatch VALUE {
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
}
if let
fn main() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "34".parse();
if let Some(color) = favorite_color {
// color would be brought in scope
println!("Using your favorite color, {color}, as the background");
} else if is_tuesday {
println!("Tuesday is green day!");
} else if let Ok(age) = age {
// age would be in scope
if age > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
}
while let
while let Some(top) = stack.pop() {
...
}
let
StatementsWhenever a let
is used, there’s a pattern involved. Formally, a let
statement looks like
let PATTERN = EXPRESSION;
// this enabled
let (x,y,z) = (1,2,3);
With that, statement like let Some(a) = some_option_value;
is possible. However, that’s not a good practice and won’t be compiled since what if the option is None? Putting that single statement does not cover all the scenario, thus, a solution is to
if let Some(a) = some_option_value {
do_things_with_a;
}
// destructuring
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
match msg {
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change color to red {r}, green {g}, and blue {b}");
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change color to hue {h}, saturation {s}, value {v}")
}
_ => (),
}
}
// Match guard
match num {
Some(x) if x % 2 == 0 => println!("The number {} is even", x),
Some(x) => println!("The number {} is odd", x),
None => (),
}