rust-lang / rust-lang/rust-clippy
explicit_iter_loop auto-fix produces non-compiling code for returned closure (needs move)
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
The clippy::explicit_iter_loop lint’s auto-fix (via cargo clippy --fix) can produce non-compiling code when the loop is inside a closure that is returned from a function.
In my case, Clippy changes for (xy, part) in grid.iter() to for (xy, part) in grid inside a returned closure, which makes the closure borrow grid instead of capturing it by value. The closure escapes the function, so this triggers E0373 (“closure may outlive the current function”).
The fix should either
- add
moveto the closure, or - avoid applying
explicit_iter_loopwhen it would cause this lifetime issue.
Reproducer
Code:
pub fn closest_in_room_range(
grid: &HashMap<RoomXY, RoomPart>,
) -> impl FnMut(RoomName, CostMatrix) -> SingleRoomCostResult + use<'_> {
|_: RoomName, mut matrix: CostMatrix| -> SingleRoomCostResult {
for (xy, part) in grid.iter() {
...
}
SingleRoomCostResult::CostMatrix(matrix)
}
}
Current output:
pub fn closest_in_room_range(
grid: &HashMap<RoomXY, RoomPart>,
) -> impl FnMut(RoomName, CostMatrix) -> SingleRoomCostResult + use<'_> {
|_: RoomName, mut matrix: CostMatrix| -> SingleRoomCostResult {
for (xy, part) in grid {
...
}
SingleRoomCostResult::CostMatrix(matrix)
}
}
Desired output:
pub fn closest_in_room_range(
grid: &HashMap<RoomXY, RoomPart>,
) -> impl FnMut(RoomName, CostMatrix) -> SingleRoomCostResult + use<'_> {
move |_: RoomName, mut matrix: CostMatrix| -> SingleRoomCostResult {
for (xy, part) in grid {
...
}
SingleRoomCostResult::CostMatrix(matrix)
}
}
Version
rustc 1.91.1 (ed61e7d7e 2025-11-07)
binary: rustc
commit-hash: ed61e7d7e242494fb7057f2657300d9e77bb4fcb
commit-date: 2025-11-07
host: x86_64-unknown-linux-gnu
release: 1.91.1
LLVM version: 21.1.2
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the explicit_iter_loop lint's auto-fix implementation and use the returned-closure reproducer in the issue to trace how the replacement affects closure capture. Add a regression test for the shown case and verify that the fixed output compiles without the E0373 error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100