You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm working on a moderately old codebase that has a number of instances of this idiom:
let z = match x {Y(z) => z,
_ => panic!()};
In other words: a match with exactly two arms, the first of which extracts "the only expected variant at this point in execution" and the other a default branch which does something (e.g. panics) if that expected variant isn't found.
This seems exactly what let-else is meant for i.e. the above would be better as:
letY(z) = x else{ panic!()};
Advantage
Advantages:
if-let is terser than the match equivalent (sometimes collapsing 4 lines down to 1).
I believe let-else, is now the expected idiom for "extract the only expected variant and if it's not found something has gone wrong".
Drawbacks
No response
Example
enumE{Y(z),A(b),C(d)}fnf(){let z = match x {Y(z) => z,
_ => p
};
...}
Could be written as:
enumE{Y(z),A(b),C(d)}fnf(){letY(z) = x else{ p };
...}
The text was updated successfully, but these errors were encountered:
warning: this could be rewritten as `let...else`
--> src/main.rs:10:3
|
10 | / let z = match x {
11 | | Y(z) => z,
12 | | _ => todo!()
13 | | };
| |____^ help: consider writing: `let Y(z) = x else { todo!() };`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else
Since it's in the pedantic category, it's allowed by default and needs to be manually enabled.
You're quite right! I've checked and this does fire on most (though not all, for reasons I haven't yet understood) instances of the idiom in our codebase. FWIW this lint doesn't feel pedantic to me, but maybe I'm biased.
Then please open another issue to change the category. I think it should be in the style passes. Anyway, better to have an issue with a title related to what you suggest so you can attract more commenters. ;)
What it does
I'm working on a moderately old codebase that has a number of instances of this idiom:
In other words: a match with exactly two arms, the first of which extracts "the only expected variant at this point in execution" and the other a default branch which does something (e.g.
panic
s) if that expected variant isn't found.This seems exactly what
let-else
is meant for i.e. the above would be better as:Advantage
Advantages:
if-let
is terser than thematch
equivalent (sometimes collapsing 4 lines down to 1).let-else
, is now the expected idiom for "extract the only expected variant and if it's not found something has gone wrong".Drawbacks
No response
Example
Could be written as:
The text was updated successfully, but these errors were encountered: