I get little confused when learning about control flow. I don't understand the difference between if-let and match.
fn main() {
let some_u8_value = Some(8u8);
// println!(" {} ", some_u8_value);
if let Some(value) = some_u8_value {
println!(" {} ", value);
} else {
println!("not a num");
}
match some_u8_value {
Some(value) => println!(" {} ", value),
None => println!("not a num"),
}
}
Why do we need if-let?
Why do we need if-let?
We don't need it, it's a convenience feature. Per RFC 160 which introduced it:
[
if let] allows for refutable pattern matching without the syntactic and semantic overhead of a full match, and without the corresponding extra rightward drift.
and
The idiomatic solution today for testing and unwrapping an Option looks like
match optVal { Some(x) => { doSomethingWith(x); } None => {} }This is unnecessarily verbose, with the
None => {}(or_ => {}) case being required, and introduces unnecessary rightward drift (this introduces two levels of indentation where a normal conditional would introduce one).[explanation of the issues with using a simple
ifwithis_someandunwrap]The if let construct solves all of these problems, and looks like this:
if let Some(x) = optVal { doSomethingWith(x); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With