rust-lang / rust-lang/rust-clippy
Warning about needless collect but suggestion does not compile
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Clippy warns about a needless collect, but the suggested code does not compile.
I have something similar to this code (condensed):
let keys = map.keys().copied().collect::<Vec<_>>();
for key in keys.into_iter() {
// since .keys() has been copied and collected, I'm not
// borrowing the map anymore and I can mutate the map here.
map.remove(key);
}
Suggestion from clippy:
warning: avoid using `collect()` when not needed
--> src/main.rs:18:5
|
18 | / let keys = map.keys().copied().collect::<Vec<_>>();
19 | |
20 | | for key in keys.into_iter() {
| |_______________^
|
= note: `#[warn(clippy::needless_collect)]` on by default
help: Use the original Iterator instead of collecting it and then producing a new one
|
18 |
19 |
20 | for key in map.keys().copied() {
|
This suggestion will not compile because maps.keys().copied() borrows the map.
Full code example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=711425060fb8ac794003067454010a69
Expectation: the warning does not appear because removing the .collect() would break the code.
Instead, this happened: the needless_collect warning triggered. Additionally, it's not possible to mute this warning for a specific line, so I resorted to adding #![allow(clippy::needless_collect)] to the entire file.
Meta
cargo +nightly clippy -V: clippy 0.0.212 (1c389ffe 2020-11-24) (I use the nightly clippy to get more warnings)rustc -Vv:
rustc 1.48.0 (7eac88abb 2020-11-16)
binary: rustc
commit-hash: 7eac88abb2e57e752f3302f02be5f3ce3d7adfb4
commit-date: 2020-11-16
host: x86_64-apple-darwin
release: 1.48.0
LLVM version: 11.0
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the needless_collect warning with the condensed example in src/main.rs or the linked Rust playground, focusing on the map mutation after collecting keys. Trace the needless_collect lint entry point and its suggested replacement; done means the lint no longer suggests removing collect when that change causes a borrow-checking error, with a regression test covering the example.
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