So, I was working on a project and came across a situation I had been in before and remain perplexed.
The language has if let
and while let
explicitly defined, but why not just make the let
statement return a bool?
For example, the code I was writing was along these lines:
// items: Vec<Item> further above.
let (modules, other): (Vec<Item>, Vec<Item>) = items.into_iter().partition(|i| {
if let Mod(_) = i.node {true} else {false}
});
whereas if it is to be believed that if let
is to reduce the need for match
when you’re looking for a specific case, the following aught to suffice:
let (modules, other): (Vec<Item>, Vec<Item>) = items.into_iter().partition(|i| let Mod(_) = i.node);
Now, I won’t argue that it’s perhaps a bit unreadable, but I don’t think that’s inherent to this method.
It could be argued that this could leave unbound variables in such a case:
let Mod(a) = b;
a.whatever()
These are currently caught by saying error[E0005]: refutable pattern in local binding
, however it could just as easily be caught in a similar way to error[E0381]: use of possibly uninitialized variable
as occurs when you use let
without specifying a value, and don’t set it in every logical path before the error. This could be accomplished by something along the lines of:
let a;
match b {
Mod(c) => {
a = c;
true
}
_ => false,
}
I can’t see any reason for it to not be implemented like this, but I would love to hear what people think