Skip to content

branches_sharing_code reporting a false positive #7452

Closed
@MGlolenstine

Description

@MGlolenstine

I tried this code:

fn test() {
    let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let mut counter = 0;
    for i in v {
        if counter == 0 {
            counter += 1;
            println!("first");
        } else if counter == 1 {
            counter += 1;
            println!("second");
        } else {
            counter += 1;
            println!("other: {}", i);
        }
    }
}

I expected to see this happen: I expected the lint to pass without a hitch, as the counter is used in the if statement.

Instead, this happened:
I got a lint report, that I could change the if statements, as they all start with the same line of code, but doing that makes the code invalid.

warning: all if blocks contain the same code at the start
 --> src/lib.rs:5:9
  |
5 | /         if counter == 0 {
6 | |             counter += 1;
  | |_________________________^
  |
  = note: `#[warn(clippy::branches_sharing_code)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#branches_sharing_code
help: consider moving the start statements out like this
  |
5 |         counter += 1;
6 |         if counter == 0 {
  |

Meta

  • cargo clippy -V: clippy 0.1.53 (53cb7b0 2021-06-17)
  • rustc -Vv:
rustc 1.53.0 (53cb7b09b 2021-06-17)
binary: rustc
commit-hash: 53cb7b09b00cbea8754ffb78e7e3cb521cb8af4b
commit-date: 2021-06-17
host: x86_64-unknown-linux-gnu
release: 1.53.0
LLVM version: 12.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions