Any way to use `&Range` for `for` loops?

Is there any way to use shared references of a std::ops::Range for for loops, instead of cloning or using mutable references ?

  • for n in &range { ... } would be best if possible, but IntoIterator is not implemented for &Range.
  • Iterator::by_ref() requires a mutable reference instead of a shared reference and not suitable for read-only concurrent tasks.
let range = 0 .. 10;
for n in &range {
    // Do something
}
for n in &range {
    // Do something else
}

Range is just a pair of integers and cloning it is cheap. You should just clone it.

Range and &Range don't implement IntoIterator because Range is an Iterator itself and reference iteration is not possible because iterator elements are not stored anywhere but it is generated and copied (thus a reference to it doesn't live long enough).

2 Likes

Aha! Now I understand why &Range don't implement IntoIterator.
I will just clone it.
Thank you.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.