Rust-clippy: same_item_push lint can trigger when the pushed value is not constant.

Created on 13 Aug 2020  路  2Comments  路  Source: rust-lang/rust-clippy

Simple example:

    let mut out = Vec::new();
    let mut i = 0;
    for _ in 0..100 {
        out.push(i);
        i += 10;
    }
    dbg!(out);

I expected to see this happen:

No clippy warning, because the value being pushed is not constant (despite the otherwise unidiomatic code, as this is a contrived example).

Instead, this happened:
The same_item_push lint throws a warning with an incorrect description of a fix.

warning: it looks like the same item is being pushed into this Vec
 --> src\main.rs:5:9
  |
5 |         out.push(i);
  |         ^^^
  |
  = note: `#[warn(clippy::same_item_push)]` on by default
  = help: try using vec![i;SIZE] or out.resize(NEW_SIZE, i)
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push

warning: 1 warning emitted

The docs at https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push say that this lint should only fire when "a for loop is used to push a constant value", but in this case the value being pushed is not constant.

Meta

  • cargo clippy -V: clippy 0.0.212 (576d27c5a 2020-08-12)
  • rustc -Vv:
    rustc 1.47.0-nightly (576d27c5a 2020-08-12) binary: rustc commit-hash: 576d27c5a6c80cd39ef57d7398831d8e177573cc commit-date: 2020-08-12 host: x86_64-pc-windows-msvc release: 1.47.0-nightly LLVM version: 10.0
L-bug

Most helpful comment

I will prepare a fix.

All 2 comments

I will prepare a fix.

We just ran into this as well with rustc 1.47.0-nightly (81dc88f88 2020-08-13)

repro:

fn main() {
    let vertlist = [0,1,2,3];
    let mut indices = vec![];
    let mut i = 0;

    for _ in 0..3 {
        let vidx = vertlist[i];
        indices.push(vidx);
        i += 1;
    }
}

causes:

warning: it looks like the same item is being pushed into this Vec
 --> src\main.rs:8:9
  |
8 |         indices.push(vidx);
  |         ^^^^^^^
  |
  = note: `#[warn(clippy::same_item_push)]` on by default
  = help: try using vec![vidx;SIZE] or indices.resize(NEW_SIZE, vidx)
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push
Was this page helpful?
0 / 5 - 0 ratings