about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--clippy_lints/src/methods/needless_collect.rs7
-rw-r--r--tests/ui/needless_collect.fixed9
-rw-r--r--tests/ui/needless_collect.rs9
3 files changed, 25 insertions, 0 deletions
diff --git a/clippy_lints/src/methods/needless_collect.rs b/clippy_lints/src/methods/needless_collect.rs
index 6732aeeb498..def7bf635da 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 e33b984a44b..8a0208e4a7e 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<Item = usize>) {}
diff --git a/tests/ui/needless_collect.rs b/tests/ui/needless_collect.rs
index fab00d67dbf..b7e8e7b90b1 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<Item = usize>) {}