Skip to content

needless_collect doesn't take into account side-effects #8055

@jsgf

Description

@jsgf

Summary

needless_collect does not take into account side effects of the iterator, and so spuriously reports a necessary collect as needless.

Lint Name

needless_collect

Reproducer

I tried this code:

pub fn filter(v: impl IntoIterator<Item = i32>) -> Result<impl Iterator<Item = i32>, usize> {
    let mut zeros = 0;

    let res: Vec<_> = v
        .into_iter()
        .filter(|i| {
            if *i == 0 {
                zeros += 1
            };
            *i != 0
        })
        .collect();

    if zeros != 0 {
        return Err(zeros);
    } 
    Ok(res.into_iter())
}

playground https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=35738bf7ad2c8bcba6b8431afd61e527

I saw this happen:

warning: avoid using `collect()` when not needed
  --> src/lib.rs:12:10
   |
12 |         .collect();
   |          ^^^^^^^
...
17 |     Ok(res.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
   |
4  ~     
5  | 
6  |     if zeros != 0 {
7  |         return Err(zeros);
8  |     } 
9  ~     Ok(v
 ...

I expected to see this happen: no warning

Version

rustc 1.56.1 (59eed8a2a 2021-11-01)
binary: rustc
commit-hash: 59eed8a2aac0230a8b53e89d4e99d55912ba6b35
commit-date: 2021-11-01
host: x86_64-unknown-linux-gnu
release: 1.56.1
LLVM version: 13.0.0

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveL-nurseryLint: Currently in the nursery group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions