Rust如何折叠if let - Clippy建议

3

我运行cargo clippy检查我的代码,并得到了clippy的反馈,他告诉我我可以通过某种方式折叠if let语句。
以下是具体的“警告”:

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 | |                     }
    | |_____________________^

我原以为可以使用&&将内部的if追加到外部if let中,但是我得到了一个警告( `let` expressions in this position are experimental,我正在使用rust版本1.57.0,而不是nightly)。

你有什么想法可以满足clippy的要求吗?

编辑:
外部的if let本身又再次嵌套在另一个if let中:
if let Some(turn) = board.getLastMove() {

而且看起来你确实可以像这样结合它们:
if let Some(Move::Normal { piece, from, to }) = board.getLastMove() {

我认为clippy lint应该包括上面的行,因为对我来说否则有点令人困惑。

编辑2:
事实证明我只是无法阅读,在上面列出的警告下面还有一些更多的信息,告诉我应该做什么。

    = 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

3
在我看来,Clippy建议你将第107行的if let嵌套到更高层的if let中,而不是将第108行的if改为在第107行使用if let。是否还有另一个层次的if let - Joe_Jingyu
1
你能做一个[MRE]吗? - Denys Séguret
@Joe_Jingyu 谢谢您指出上面的那行可能是相关的,我只关注输出中显示的行 - Teiem
2
请尝试将两个 if let 语句合并为一个:if let Some(Move::Normal { piece, from, to }) = board.getLastMove() - Joe_Jingyu
最简单的示例看起来像这样:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5c7f964314fd2414c6063877c691afed 但在这种情况下,Clippy会显示带有确切建议的“help”消息。如果您的情况中没有这样的消息,请提供您的复现。 - Cerberus
1个回答

0

写:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接