Skip to content

Commit efc4c6c

Browse files
committed
extend single_element_loop to match .iter()
1 parent 08e36d7 commit efc4c6c

File tree

4 files changed

+33
-2
lines changed

4 files changed

+33
-2
lines changed

clippy_lints/src/loops/single_element_loop.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,14 @@ 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.name == rustc_span::sym::iter => {
20+
&args[0]
21+
},
22+
_ => return,
23+
};
1724
if_chain! {
18-
if let ExprKind::AddrOf(BorrowKind::Ref, _, arg_expr) = arg.kind;
1925
if let PatKind::Binding(.., target, _) = pat.kind;
2026
if let ExprKind::Array([arg_expression]) = arg_expr.kind;
2127
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)