Lint against needless uses of collect()
Handles cases of `.collect().len()`, `.collect().is_empty()`, and `.collect().contains()`. This lint is intended to be generic enough to be added to at a later time with other similar patterns that could be optimized. Closes #3034
This commit is contained in:
parent
c0513097ab
commit
fbc93c0166
5 changed files with 122 additions and 0 deletions
10
tests/ui/needless_collect.rs
Normal file
10
tests/ui/needless_collect.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
#[warn(clippy, needless_collect)]
|
||||
#[allow(unused_variables, iter_cloned_collect)]
|
||||
fn main() {
|
||||
let sample = [1; 5];
|
||||
let len = sample.iter().collect::<Vec<_>>().len();
|
||||
if sample.iter().collect::<Vec<_>>().is_empty() {
|
||||
// Empty
|
||||
}
|
||||
sample.iter().cloned().collect::<Vec<_>>().contains(&1);
|
||||
}
|
||||
22
tests/ui/needless_collect.stderr
Normal file
22
tests/ui/needless_collect.stderr
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
error: you are collecting an iterator to check its length
|
||||
--> $DIR/needless_collect.rs:5:15
|
||||
|
|
||||
5 | let len = sample.iter().collect::<Vec<_>>().len();
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing with: `sample.iter().count()`
|
||||
|
|
||||
= note: `-D needless-collect` implied by `-D warnings`
|
||||
|
||||
error: you are collecting an iterator to check if it is empty
|
||||
--> $DIR/needless_collect.rs:6:8
|
||||
|
|
||||
6 | if sample.iter().collect::<Vec<_>>().is_empty() {
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing with: `sample.iter().any(|_| true)`
|
||||
|
||||
error: you are collecting an iterator to check if contains an element
|
||||
--> $DIR/needless_collect.rs:9:5
|
||||
|
|
||||
9 | sample.iter().cloned().collect::<Vec<_>>().contains(&1);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing with: `sample.iter().cloned().any(|&x| x == 1)`
|
||||
|
||||
error: aborting due to 3 previous errors
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue