Skip to content

clippy::needless_collect although collect is needed #9191

@drwadu

Description

@drwadu

Summary

suppose we have the following code snippet where ys is of type std::collections::HashSet:

                    if xs
                        .clone()
                        .iter()
                        .map(|x| ys.remove(x))
                        .collect::<Vec<_>>()
                        .contains(&true)
                    {  // do something

we want to try to remove every element in xs from ys; if x is in ys, then ys.remove() returns true, otherwise false. now, clippy suggests:

avoid using `collect()` when not needed

help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: replace with: `any(|x| x == true)`clippy(clippy::needless_collect)

However, as far as I understand, using any will cause the iterator not only to stop, whenever the first true is found (since any is short-circuiting), but also stop trying to remove elements, whenever one element was actually removed. I need to remove every element contained in xs and ys, which apparently does not work using any, therefore I (if I am not mistaken) need collect. I was trying to use any in the first place, as I am trying to avoid collecting, whenever possible. However, in this situation, I feel like I cannot avoid it (it stopped after the removal of the first element), but clippy is telling me to avoid it.

Lint Name

clippy::needless_collect

Version

rustc 1.58.1 (db9d1b20b 2022-01-20)
binary: rustc
commit-hash: db9d1b20bba1968c1ec1fc49616d4742c1725b4b
commit-date: 2022-01-20
host: x86_64-unknown-linux-gnu
release: 1.58.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