So I’m learning Rust and I’m learning about pattern matching and "if let" statements as alternatives to matching expressions. I was watching this video regarding "if let" which is mentioned at 11:00 and they give this example:
fn main() {
let some_value: Option<i32> = Some(3);
if let Some(3) = some_value {
println!("three");
}
}
I get that this is useful if you only have one specific pattern you want to match and the matching expression is too verbose, but if this is the case, couldn’t you simply do this?:
fn main() {
let some_value: Option<i32> = Some(3);
if some_value == Some(3) {
println!("three");
}
}
Is there something about this expression that is inferior to the "if let" statement that I’m not aware of?
>Solution :
The if let form lets you be more generic than your example. You can’t do if some_value == Some(n) unless n is defined, but you can do:
if let Some(n) = some_value { ... }
Where that now gives you an n you can work with.
I think you’ll find as you work with Rust more that the match form Some(n) shows up a lot more often than Some(1) for some specific value.
Don’t forget you can also do this:
if let Some(1) | Some(2) = some_value { ... }
Where that’s a lot more thorny with a regular if unless you’re using matching like this:
if matches!(some_value, Some(1) | Some(2)) { ... }
So there’s a number of useful options here that might fit better in some situations.
Don’t forget about
cargo clippywhich will point out if there’s better ways of expressing something.