From 6321ac79e1a24b4be336a8b6f3dd426251b773d4 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 17 Feb 2025 13:06:57 -0700 Subject: [PATCH] needless_collect: look through assignments, not just declarations --- clippy_lints/src/methods/needless_collect.rs | 7 +++++++ tests/ui/needless_collect.fixed | 9 +++++++++ tests/ui/needless_collect.rs | 9 +++++++++ 3 files changed, 25 insertions(+) diff --git a/clippy_lints/src/methods/needless_collect.rs b/clippy_lints/src/methods/needless_collect.rs index 6732aeeb4985..def7bf635daf 100644 --- a/clippy_lints/src/methods/needless_collect.rs +++ b/clippy_lints/src/methods/needless_collect.rs @@ -546,6 +546,12 @@ impl<'tcx> Visitor<'tcx> for IteratorMethodCheckVisitor<'_, 'tcx> { && !is_trait_method(self.cx, expr, sym::Iterator) { return ControlFlow::Break(()); + } else if let ExprKind::Assign(place, value, _span) = &expr.kind + && value.hir_id == self.hir_id_of_expr + && let Some(id) = path_to_local(place) + { + // our iterator was directly assigned to a variable + self.hir_id_of_let_binding = Some(id); } walk_expr(self, expr) } @@ -561,6 +567,7 @@ impl<'tcx> Visitor<'tcx> for IteratorMethodCheckVisitor<'_, 'tcx> { }) = &stmt.kind && expr.hir_id == self.hir_id_of_expr { + // our iterator was directly assigned to a variable self.hir_id_of_let_binding = Some(*id); } walk_stmt(self, stmt) diff --git a/tests/ui/needless_collect.fixed b/tests/ui/needless_collect.fixed index e33b984a44b5..8a0208e4a7ed 100644 --- a/tests/ui/needless_collect.fixed +++ b/tests/ui/needless_collect.fixed @@ -87,6 +87,15 @@ fn main() { let my_collection: Vec<()> = vec![()].into_iter().map(|()| {}).collect(); let my_iter = my_collection.into_iter(); let _sliced = my_iter.as_slice(); + // Assignment outside of main scope + { + let x; + { + let xxx: Vec<()> = vec![()].into_iter().map(|()| {}).collect(); + x = xxx.into_iter(); + for i in x.as_slice() {} + } + } } fn foo(_: impl IntoIterator) {} diff --git a/tests/ui/needless_collect.rs b/tests/ui/needless_collect.rs index fab00d67dbfd..b7e8e7b90b14 100644 --- a/tests/ui/needless_collect.rs +++ b/tests/ui/needless_collect.rs @@ -87,6 +87,15 @@ fn main() { let my_collection: Vec<()> = vec![()].into_iter().map(|()| {}).collect(); let my_iter = my_collection.into_iter(); let _sliced = my_iter.as_slice(); + // Assignment outside of main scope + { + let x; + { + let xxx: Vec<()> = vec![()].into_iter().map(|()| {}).collect(); + x = xxx.into_iter(); + for i in x.as_slice() {} + } + } } fn foo(_: impl IntoIterator) {}