Skip to content

Suggest using a range iterator instead of casting enumerate() #14560

Open
@kpreid

Description

@kpreid

What it does

Iterator::enumerate() is not the only way to produce an ascending sequence of indices; (0..) does as well, and can be combined with zip() to get the same output of pairs. This can be useful when an index of a type other than usize is needed. The lint should suggest using (0..).zip(iter) over iter.enumerate() in cases where the index produced by enumerate() is immediately converted to another type which implements core::iter::Step.

Advantage

  • Simpler code.
  • Avoids creating a value of the wrong type before the correct type.
  • Avoids introducing a variable or repeated code if the typed index needs to be used more than once.

Drawbacks

  • Could be considered to hide the possibility of overflow, though neither version is correct in that case.
  • enumerate() is a familiar operation, and so zip()ping an unbounded range may be less obvious.

Example

pub fn example1(data: &mut [Vec<u8>]) {
    for (i, v) in data.iter_mut().enumerate() {
        v.push(i as u8);
    }
}

Could be written as:

pub fn example2(data: &mut [Vec<u8>]) {
    for (i, v) in (0..).zip(data.iter_mut()) {
        v.push(i);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions