Rust if let and Patterns
if let and while let match one pattern without writing a full match. Patterns can destructure tuples, structs and enums, and add guards with if.
ExampleRust
struct Point {
x: i32,
y: i32,
}
fn main() {
let maybe: Option<i32> = Some(7);
if let Some(n) = maybe {
println!("got {}", n);
}
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {}", top);
}
let p = Point { x: 3, y: 0 };
match p {
Point { x, y: 0 } => println!("on the x axis at {}", x),
Point { x: 0, y } => println!("on the y axis at {}", y),
Point { x, y } => println!("at {},{}", x, y),
}
let n = 15;
let kind = match n {
x if x % 15 == 0 => "fizzbuzz",
x if x % 3 == 0 => "fizz",
_ => "other",
};
println!("{}", kind);
}Output
got 7 popped 3 popped 2 popped 1 on the x axis at 3 fizzbuzz
Quick check
What is if let for?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.