21.14 if let
and while let
When matching only one pattern of interest, if let
and while let
can be more succinct than 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); } }
Note: The syntax
if let Some(value) = some_option
means “try to matchsome_option
against the patternSome(value)
. If it matches, execute the block withvalue
bound to the inner field. If it doesn’t match, skip the block.” This is shorter than amatch
when you only care about a single pattern.
21.14.2 if let
With else
if let ... else
allows for an alternative if the pattern fails:
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
runs as long as a pattern continues to match:
fn main() { let mut numbers = vec![1, 2, 3]; while let Some(num) = numbers.pop() { println!("Got {}", num); } println!("No more numbers!"); }