Range loop used only to index the collection it spans

ID

rust.performance.needless_range_loop

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Inefficient Api Usage

Language

Rust

Description

The loop counts over the length of the collection only to index it back, which costs a bounds check on every access and can panic if the collection is resized inside the loop. Iterate the collection directly with for value in &values, or with enumerate() when the index is also needed.

Rationale

The loop counts over the length of the collection only to index it back, which costs a bounds check on every access and can panic if the collection is resized inside the loop. Iterate the collection directly with for value in &values, or with enumerate() when the index is also needed.

The following code illustrates the pattern detected by this rule:

fn total(values: &[u32]) -> u32 {
    let mut sum = 0;
    for i in 0..values.len() {
        // FLAGGED: Range loop used only to index the collection it spans
        sum += values[i];
    }
    sum
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved