rust-lang / rust-lang/rust-clippy

Basic while loops => for loops

Open
#15,046 0 comments 0 reactions 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

In the wild I've seen people explain Rust using while loops where a basic for loop suffices (https://mmhaskell.com/blog/2025/6/9/spatial-reasoning-with-zigzag-patterns ). So I think Clippy could suggest to use a for loop in such basic cases.

Advantage

For such basic cases a for loop seems the best solution in Rust.

Drawbacks

If this lint suggests to replace while loops with a step different from 1, it risks introducing code that's slower (see https://github.com/rust-lang/rust/issues/141360 ). So I suggest to avoid suggesting this replacement if the step is a run-time value (until that performance problem gets sorted out).

Example
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

const fn foo1(a: usize, b: usize) -> usize {
    let mut tot = 0;
    let mut i = a;
    while i < b {
        tot += i;
        i += 1;
    }
    tot
}

const fn foo3(a: usize, b: usize, step: usize) -> usize {
    let mut tot = 0;
    let mut i = a;
    while i < b {
        tot += i;
        i += step;
    }
    tot
}

fn main() {
    dbg!(foo1(2, 20)); // 189
    dbg!(foo3(2, 20, 3)); // 57
}

Could be written as:

fn foo2(a: usize, b: usize) -> usize {
    let mut tot = 0;
    for i in a .. b {
        tot += i;
    }
    tot
}

fn foo4(a: usize, b: usize, step: usize) -> usize {
    let mut tot = 0;
    for i in (a .. b).step_by(step) {
        tot += i;
    }
    tot
}

fn main() {
    dbg!(foo2(2, 20)); // 189
    dbg!(foo4(2, 20, 3)); // 57
}

The case foo4 coud be better left as in the foo2 code.

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 with the foo1 and foo3 examples and review the linked Rust performance issue before defining the lint's scope. The completed behavior should suggest a range-based for loop for the basic increment-by-one case while avoiding runtime-step replacements unless their performance is acceptable.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.