Skip to content

Can't use DoubleEndedIterator for inclusive ranges  #66195

Open
@kacejot

Description

@kacejot

Code:

fn main() {
    let size = 10;
    let h = size / 2;
    let _iter = (-h..=h).step_by(size as usize).rev();
}

Error:

error[E0277]: the trait bound `std::ops::RangeInclusive<i32>: std::iter::ExactSizeIterator` is not satisfied
 --> src/main.rs:4:48
  |
4 |     let iter = (-h..=h).step_by(size as usize).rev();
  |                                                ^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `std::ops::RangeInclusive<i32>`
  |
  = help: the following implementations were found:
            <std::ops::RangeInclusive<i16> as std::iter::ExactSizeIterator>
            <std::ops::RangeInclusive<i8> as std::iter::ExactSizeIterator>
            <std::ops::RangeInclusive<u16> as std::iter::ExactSizeIterator>
            <std::ops::RangeInclusive<u8> as std::iter::ExactSizeIterator>
  = note: required because of the requirements on the impl of `std::iter::DoubleEndedIterator` for `std::iter::StepBy<std::ops::RangeInclusive<i32>>`

I think Rust is not getting safer without ExactSizeIterator implementation for RangeInclusive. The behavior like the one above is not obvious for average Rust coder. Moreover, the workaround exists:

fn main() {
    let size = 10;
    let h = size / 2;
    let _iter = (-h..h+1).step_by(size as usize).rev();
}

related: #36386

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-iteratorsArea: IteratorsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions