Reputation: 145
Code:
let x = Some(3);
if x == Some(3) {
println!("if case");
}
if let Some(3) = x {
println!("if let case");
}
Result:
if case
if let case
Why do rust programmers use "if let" ?
Upvotes: 5
Views: 193
Reputation: 20579
With if let
, you can use pattern matching to decompose x
into parts:
let x = Some(3);
if let Some(v) = x {
println!("{}", v); // prints 3
}
The same thing with if
is inelegant:
let x = Some(3);
if x.is_some() {
println!("{}", x.unwrap()); // not recommended
}
Upvotes: 8