Skip to content

Fix an invalid suggestion in needless_collect test #6202

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion clippy_lints/src/loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3001,7 +3001,14 @@ impl IterFunction {
IterFunctionKind::IntoIter => String::new(),
IterFunctionKind::Len => String::from(".count()"),
IterFunctionKind::IsEmpty => String::from(".next().is_none()"),
IterFunctionKind::Contains(span) => format!(".any(|x| x == {})", snippet(cx, *span, "..")),
IterFunctionKind::Contains(span) => {
let s = snippet(cx, *span, "..");
if let Some(stripped) = s.strip_prefix('&') {
format!(".any(|x| x == {})", stripped)
} else {
format!(".any(|x| x == *{})", s)
}
},
}
}
fn get_suggestion_text(&self) -> &'static str {
Expand Down
6 changes: 6 additions & 0 deletions tests/ui/needless_collect_indirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,10 @@ fn main() {
.into_iter()
.map(|x| (*x, *x + 1))
.collect::<HashMap<_, _>>();

// #6202
let a = "a".to_string();
let sample = vec![a.clone(), "b".to_string(), "c".to_string()];
let non_copy_contains = sample.into_iter().collect::<Vec<_>>();
non_copy_contains.contains(&a);
}
17 changes: 15 additions & 2 deletions tests/ui/needless_collect_indirect.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,21 @@ LL | | indirect_contains.contains(&&5);
help: Check if the original Iterator contains an element instead of collecting then checking
|
LL |
LL | sample.iter().any(|x| x == &&5);
LL | sample.iter().any(|x| x == &5);
|

error: aborting due to 4 previous errors
error: avoid using `collect()` when not needed
--> $DIR/needless_collect_indirect.rs:23:5
|
LL | / let non_copy_contains = sample.into_iter().collect::<Vec<_>>();
LL | | non_copy_contains.contains(&a);
| |____^
|
help: Check if the original Iterator contains an element instead of collecting then checking
|
LL |
LL | sample.into_iter().any(|x| x == a);
|

error: aborting due to 5 previous errors