rust-lang / rust-lang/rust-clippy

Needless collect suggestion does not compile

Open
#8,046 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error 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 A;
impl A {
    fn foo(&mut self) -> i32 {
        0
    }
}

fn f1() {
    let mut a = A {};

    let v = (0..10).map(|_| a.foo()).collect::<Vec<_>>();
    for (i, n) in v.into_iter().enumerate() {
        a.foo();
    }
}

As iterators are lazy, I have to collect the iterator to avoid having multiple mutable references to a, as a.foo() is called within the loop. If this did compile, it could also change the logic of the code if a.foo actually did something.

Here is a playgound link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7b7c73582c583be34dabe4deccbdb7ea

I expected to see this happen: The warning would not appear.

Instead, this happened: Clippy wants me to remove the collect. However, this results in the compiler error: cannot borrow a as mutable more than once at a time.

Meta

Rust version (rustc -Vv):

rustc 1.46.0-nightly (f455e46ea 2020-06-20)
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

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 case from the issue in the linked Rust Playground and compare the lint suggestion with the compiler error after removing collect. Trace the needless_collect lint entry point and its tests, then add coverage showing that this pattern does not receive an invalid suggestion while preserving valid suggestions.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.