Skip to content

Warn when iterating an array of ranges #7125

Closed
@teor2345

Description

@teor2345

What it does

Warns users if they accidentally iterate range struct items, rather than iterating through the indexes in the range:

Suggests:

  • iterating through the indexes in the range, or
  • disambiguating the range struct iteration by providing a range type.

This lint will become more important once rustc allows iterating arrays by value, because that allows code like:

for _ in [0..5] {} // iterates through 1 range, not 5 indexes

For context, see rust-lang/rust#84147 (comment)

Categories (optional)

  • Kind: clippy::correctness

What is the advantage of the recommended code over the original code

The recommended code either:

  • does what the user actually intended, or
  • makes it clear that the user intended something really unusual (iterating ranges themselves, not their indexes).

Drawbacks

Expressing iterating through an array of ranges becomes more verbose. But this disambiguation makes the intent of the code much clearer.

Example

for _ in [0..5] {} // iterates through 1 range, clippy warning

Is probably intended to be:

for _ in 0..5 {} // iterates through 5 indexes

And if range iteration is genuinely intended, it could be disambiguated as:

for _: Range<_> in [0..5] {} // iterates through 1 range, no clippy warning

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsC-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions