rust-lang / rust-lang/rust-clippy

Add `for_loopable_loop` which converts loops into for range loops

Open
#16,586 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

This lint converts loops that increment a state counter into for range loops. It should be able to handle infinite loops (using an unbounded range) as well as loops that stop iteration once they reach a certain iteration count.

Advantage
  • Reduces the amount of mutable state to track when reading the code
  • Makes it clearer how many iterations the loop would run for
  • More idiomatic
Drawbacks
  • Using a loop may make more sense semantically if the loop was written to update a shared state and just so happens to increment a counter on every iteration.
Example
let mut i = 0;
loop {
    println!("Loop iteration: {i}");
    i += 1;
}

Could be written as:

for i in 0.. {
    println!("Loop iteration: {i}");
}

The lint could also handle breaking out of the loop

let mut i = 0;
loop {
    println!("Loop iteration: {i}");
    i += 1;
    if i >= 5 {
        break
    }
}

Could be written as:

for i in 0..5 {
    println!("Loop iteration: {i}");
}
Comparison with existing lints

Unlike clippy::explicit_counter_loop this lint works even when the loop is not iterating over a slice.

Additional Context

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by comparing the proposed behavior with the existing clippy::explicit_counter_loop lint and the two loop examples in the issue. The work is done when the lint covers both unbounded loops and loops that break at a specified iteration count while preserving the stated semantic caveat.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.