Skip to content

Commit 6321ac7

Browse files
committed
needless_collect: look through assignments, not just declarations
1 parent c012693 commit 6321ac7

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

clippy_lints/src/methods/needless_collect.rs

+7
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,12 @@ impl<'tcx> Visitor<'tcx> for IteratorMethodCheckVisitor<'_, 'tcx> {
546546
&& !is_trait_method(self.cx, expr, sym::Iterator)
547547
{
548548
return ControlFlow::Break(());
549+
} else if let ExprKind::Assign(place, value, _span) = &expr.kind
550+
&& value.hir_id == self.hir_id_of_expr
551+
&& let Some(id) = path_to_local(place)
552+
{
553+
// our iterator was directly assigned to a variable
554+
self.hir_id_of_let_binding = Some(id);
549555
}
550556
walk_expr(self, expr)
551557
}
@@ -561,6 +567,7 @@ impl<'tcx> Visitor<'tcx> for IteratorMethodCheckVisitor<'_, 'tcx> {
561567
}) = &stmt.kind
562568
&& expr.hir_id == self.hir_id_of_expr
563569
{
570+
// our iterator was directly assigned to a variable
564571
self.hir_id_of_let_binding = Some(*id);
565572
}
566573
walk_stmt(self, stmt)

tests/ui/needless_collect.fixed

+9
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ fn main() {
8787
let my_collection: Vec<()> = vec![()].into_iter().map(|()| {}).collect();
8888
let my_iter = my_collection.into_iter();
8989
let _sliced = my_iter.as_slice();
90+
// Assignment outside of main scope
91+
{
92+
let x;
93+
{
94+
let xxx: Vec<()> = vec![()].into_iter().map(|()| {}).collect();
95+
x = xxx.into_iter();
96+
for i in x.as_slice() {}
97+
}
98+
}
9099
}
91100

92101
fn foo(_: impl IntoIterator<Item = usize>) {}

tests/ui/needless_collect.rs

+9
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ fn main() {
8787
let my_collection: Vec<()> = vec![()].into_iter().map(|()| {}).collect();
8888
let my_iter = my_collection.into_iter();
8989
let _sliced = my_iter.as_slice();
90+
// Assignment outside of main scope
91+
{
92+
let x;
93+
{
94+
let xxx: Vec<()> = vec![()].into_iter().map(|()| {}).collect();
95+
x = xxx.into_iter();
96+
for i in x.as_slice() {}
97+
}
98+
}
9099
}
91100

92101
fn foo(_: impl IntoIterator<Item = usize>) {}

0 commit comments

Comments
 (0)