rust: non-destructuring if let
In Rust, if let chains are fantastic, but it seems that most of the time they are used to destructure things, like
if let Some(x) = foo()
&& let Ok(y) = x.bar()
{ ... }
Recently I saw an even simpler, but really useful way of using them:
if let Some(x) = foo()
&& let y = x.bar()
&& y.cond1()
&& y.cond2()
{ ... }
The fact that you can just assign y and don’t have to open up a whole new nested if has somehow escaped me up until now, even though it is completely obvious.
Another example that I would definitely have written with two nested ifs before:
fn foo(xs: Vec<usize>) {
if !xs.is_empty()
&& let max = *xs.iter().max().unwrap()
&& max > 0
{ ... }
}