21.14 if let
and while let
When you only care about matching one pattern and ignoring everything else, if let
and while let
offer convenient shortcuts over a full match
.
21.14.1 if let
Without else
fn main() { let some_option = Some(5); // Using match match some_option { Some(value) => println!("The value is {}", value), _ => (), } // Equivalent if let if let Some(value) = some_option { println!("The value is {}", value); } }
21.14.2 if let
With else
fn main() { let some_option = Some(5); if let Some(value) = some_option { println!("The value is {}", value); } else { println!("No value!"); } }
Combining if let
, else if
, and else if let
fn main() { let some_option = Some(5); let another_value = 10; if let Some(value) = some_option { println!("Matched Some({})", value); } else if another_value == 10 { println!("another_value is 10"); } else if let None = some_option { println!("Matched None"); } else { println!("No match"); } }
21.14.3 while let
while let
repeatedly matches the same pattern as long as it succeeds:
fn main() { let mut numbers = vec![1, 2, 3]; while let Some(num) = numbers.pop() { println!("Got {}", num); } println!("No more numbers!"); }