rust-lang / rust-lang/rust-clippy
Incorrect report of needless collect with the sequence from_fn().collect() follow by vec.into_iter().rev().collect()
Open
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
Summary
The iterator in front of the first collect is not bi-directional. clippy fail at identify that the subsequent rev() would not accept it if the operation were chained as suggested.
Lint Name
needless_collect
Reproducer
I tried this code:
fn main() {
let mut i = 0;
let a = std::iter::from_fn(move || {
i += 1;
if i < 10 {
Some(i)
} else {
None
}
})
.collect::<Vec<usize>>();
println!("{:?}", a.into_iter().rev().collect::<Vec<usize>>());
}
I saw this happen:
warning: avoid using `collect()` when not needed
--> src/main.rs:11:6
|
11 | .collect::<Vec<usize>>();
| ^^^^^^^
12 | println!("{:?}", a.into_iter().rev().collect::<Vec<usize>>());
| ------------- 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
|
3 ~
4 ~ println!("{:?}", std::iter::from_fn(move || {
5 + i += 1;
6 + if i < 10 {
7 + Some(i)
8 + } else {
...
warning: `playground` (bin "playground") generated 1 warning
I expected to see this happen:
Version
No response
Additional Labels
l-suggestion-causes-error
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
The supplied Rust reproducer and the needless_collect lint are the starting points. Run the reproducer, then inspect how the lint reasons about the iterator before collect and the later rev; done means Clippy no longer emits a suggestion that would fail to compile.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100