Teiem
Teiem

Reputation: 1629

rust how to collapse if let - clippy suggestion

I run cargo clippy to get some feedback on my code and clippy told me that I can somehow collapse a if let.
Here is the exact "warning":

warning: this `if let` can be collapsed into the outer `if let`
   --> src\main.rs:107:21
    |
107 | /                     if let Move::Normal { piece, from, to } = turn {
108 | |                         if i8::abs(from.1 - to.1) == 2 && piece.getColor() != *color && to.0 == x {
109 | |                             let offsetX = x - to.0;
110 | |
...   |
116 | |                         }
117 | |                     }
    | |_____________________^

I thought I could maybe just append the inner if using && but then i get a warning ( `let` expressions in this position are experimental, I am using rust version 1.57.0, not nightly).

Any idea what clippy wants me to do?

Edit:
the outer if let is itself again inside another if let:
if let Some(turn) = board.getLastMove() {

And it seems you can indeed combine them like so:
if let Some(Move::Normal { piece, from, to }) = board.getLastMove() {

In my opinion the clippy lint should include the line above as it is otherwise, at least for me, somewhat confusing

Edit 2:
Turns out I just cant read, below the warning listed above was some more information telling me exactly what to do.

    = note: `#[warn(clippy::collapsible_match)]` on by default
help: the outer pattern can be modified to include the inner pattern
   --> src\main.rs:126:29
    |
126 |                 if let Some(turn) = board.getLastMove() {
    |                             ^^^^ replace this binding
127 |                     if let Move::Normal { piece, from, to } = turn {
    |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ with this pattern
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_match

Upvotes: 3

Views: 1446

Answers (1)

GintsGints
GintsGints

Reputation: 855

Write:

if let Some(Move::Normal { piece, from, to }) = board.getLastMove() {
}

Upvotes: 0

Related Questions