if let
For some use cases, when matching enums, match
is awkward. For example:
#![allow(unused_variables)]
fn main() {
// Make `optional` of type `Option<i32>`
let optional = Some(7);
match optional {
Some(i) => {
println!("This is a really long string and `{:?}`", i);
// ^ Needed 2 indentations just so we could destructure
// `i` from the option.
},
_ => {},
// ^ Required because `match` is exhaustive. Doesn't it seem
// like wasted space?
};
}
if let
is cleaner for this use case and in addition allows various
failure options to be specified:
In the same way, if let
can be used to match any enum value: