Loop keeping its own index counter instead of using enumerate()

ID

rust.maintainability.explicit_counter_loop

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Inefficient Api Usage

Language

Rust

Description

Reports a for loop preceded by a counter binding that the body increments by one on every pass, which is the index enumerate() already provides.

Rationale

The counter and the loop are only related by convention, so nothing stops a later edit from adding a continue, an early increment or a second increment path and silently putting the index out of step with the item. The binding also stays alive and mutable after the loop ends, which reads as if the final value mattered.

The following code illustrates the pattern detected by this rule:

pub fn numbered(names: &[String]) {
    // FLAGGED: Loop keeping its own index counter instead of using enumerate()
    let mut index = 0;
    for name in names {
        println!("{}: {}", index, name);
        index += 1;
    }
}

Remediation

Iterate with for (index, item) in collection.iter().enumerate() and delete the counter. Where the count really is the result rather than an index, filter(…​).count() states that directly.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved