rust-lang / rust-lang/rust-clippy

needless_collect false positives around borrowing

Open
#7,526 5 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive L-nursery
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Lint name: needless_collect

I tried this code:

struct Foo(Vec<u8>);

impl Foo {
    fn get_iterator(&self) -> impl Iterator<Item = u8> {
        let items: Vec<_> = self.0.iter().filter(|x| **x > 0).copied().collect();
        items.into_iter()
    }
}

(playpen)

I expected to see this happen: No lint, because removing the collect produces an iterator that borrows from self

Instead, this happened:

warning: avoid using `collect()` when not needed
 --> src/main.rs:5:72
  |
5 |         let items: Vec<_> = self.0.iter().filter(|x| **x > 0).copied().collect();
  |                                                                        ^^^^^^^
6 |         items.into_iter()
  |         ----------------- the iterator could be used here instead
  |
  = note: `#[warn(clippy::needless_collect)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: use the original Iterator instead of collecting it and then producing a new one
  |
5 |         
6 |         self.0.iter().filter(|x| **x > 0).copied()
  |
Meta
  • cargo clippy -V: clippy 0.1.54 (a178d03 2021-07-26)
  • rustc -Vv:
rustc 1.54.0 (a178d0322 2021-07-26)
binary: rustc
commit-hash: a178d0322ce20e33eac124758e837cbd80a6f633
commit-date: 2021-07-26
host: x86_64-unknown-linux-gnu
release: 1.54.0
LLVM version: 12.0.1rustc 1.54.0 (a178d0322 2021-07-26)
binary: rustc
commit-hash: a178d0322ce20e33eac124758e837cbd80a6f633
commit-date: 2021-07-26
host: x86_64-unknown-linux-gnu
release: 1.54.0
LLVM version: 12.0.1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the needless_collect warning with the Rust example in the issue by running cargo clippy. Start at the needless_collect lint entry point, then add coverage for the borrowing case so the lint does not suggest removing a collect when that would return an iterator borrowing from self.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.