Skip to content

Commit 8f0f76b

Browse files
committed
Auto merge of #7132 - rust-lang:single_element_loop_iter, r=Manishearth
extend `single_element_loop` to match `.iter()` This extends `single_element_loop` to also match `[..].iter()` in the loop argument. Related to #7125, but not completely fixing it due to the lint only firing if the array expression contains a local variable. --- changelog: none
2 parents c4e2d36 + 0e44540 commit 8f0f76b

File tree

4 files changed

+31
-2
lines changed

4 files changed

+31
-2
lines changed

clippy_lints/src/loops/single_element_loop.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ pub(super) fn check<'tcx>(
1414
body: &'tcx Expr<'_>,
1515
expr: &'tcx Expr<'_>,
1616
) {
17+
let arg_expr = match arg.kind {
18+
ExprKind::AddrOf(BorrowKind::Ref, _, ref_arg) => ref_arg,
19+
ExprKind::MethodCall(method, _, args, _) if args.len() == 1 && method.ident.as_str() == "iter" => &args[0],
20+
_ => return,
21+
};
1722
if_chain! {
18-
if let ExprKind::AddrOf(BorrowKind::Ref, _, arg_expr) = arg.kind;
1923
if let PatKind::Binding(.., target, _) = pat.kind;
2024
if let ExprKind::Array([arg_expression]) = arg_expr.kind;
2125
if let ExprKind::Path(ref list_item) = arg_expression.kind;

tests/ui/single_element_loop.fixed

+5
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,9 @@ fn main() {
88
let item = &item1;
99
println!("{}", item);
1010
}
11+
12+
{
13+
let item = &item1;
14+
println!("{:?}", item);
15+
}
1116
}

tests/ui/single_element_loop.rs

+4
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,8 @@ fn main() {
77
for item in &[item1] {
88
println!("{}", item);
99
}
10+
11+
for item in [item1].iter() {
12+
println!("{:?}", item);
13+
}
1014
}

tests/ui/single_element_loop.stderr

+17-1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,21 @@ LL | println!("{}", item);
1515
LL | }
1616
|
1717

18-
error: aborting due to previous error
18+
error: for loop over a single element
19+
--> $DIR/single_element_loop.rs:11:5
20+
|
21+
LL | / for item in [item1].iter() {
22+
LL | | println!("{:?}", item);
23+
LL | | }
24+
| |_____^
25+
|
26+
help: try
27+
|
28+
LL | {
29+
LL | let item = &item1;
30+
LL | println!("{:?}", item);
31+
LL | }
32+
|
33+
34+
error: aborting due to 2 previous errors
1935

0 commit comments

Comments
 (0)