Skip to content

False positive branches_sharing_code: different inferred type #7053

Closed
@dtolnay

Description

@dtolnay
fn main() {
    if true {
        let mut v = Vec::new();
        v.push(0);
    } else {
        let mut v = Vec::new();
        v.push("");
    };
}
$ cargo clippy
warning: all if blocks contain the same code at the start
 --> src/main.rs:2:5
  |
2 | /     if true {
3 | |         let mut v = Vec::new();
  | |_______________________________^
  |
  = 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
  |
2 |     let mut v = Vec::new();
3 |     if true {
  |

Clippy's preferred code is the following, which does not compile.

fn main() {
    let mut v = Vec::new();
    if true {
        v.push(0);
    } else {
        v.push("");
    };
}
error[E0308]: mismatched types
 --> src/main.rs:6:16
  |
6 |         v.push("");
  |                ^^ expected integer, found `&str`

Meta

  • cargo clippy -V: clippy 0.1.53 (2e495d2 2021-04-08)
  • rustc -Vv:
    rustc 1.53.0-nightly (2e495d2e8 2021-04-08)
    binary: rustc
    commit-hash: 2e495d2e845cf27740e3665f718acfd3aa17253e
    commit-date: 2021-04-08
    host: x86_64-unknown-linux-gnu
    release: 1.53.0-nightly
    LLVM version: 12.0.0
    

Mentioning @xFrednet @phansch #6463

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions