Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a range of generic type

I have a trait

trait B {
    type Index: Sized + Copy;
    fn bounds(&self) -> (Self::Index, Self::Index);
}

I want to get all the Indexes within bounds:

fn iterate<T: B>(it: &T) {
    let (low, high) = it.bounds();
    for i in low..high {}
}

This won't work since there's no constraint that the type T can be "ranged" over, and the compiler says as much:

error[E0277]: the trait bound `<T as B>::Index: std::iter::Step` is not satisfied
 --> src/main.rs:8:5
  |
8 |     for i in low..high {}
  |     ^^^^^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `<T as B>::Index`
  |
  = help: consider adding a `where <T as B>::Index: std::iter::Step` bound
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::Range<<T as B>::Index>`

I tried adding the Step bound to Index

use std::iter::Step;

trait B {
    type Index: Sized + Copy + Step;
    fn bounds(&self) -> (Self::Index, Self::Index);
}

but apparently it isn't stable:

error: use of unstable library feature 'step_trait': likely to be replaced by finer-grained traits (see issue #42168)
 --> src/main.rs:1:5
  |
1 | use std::iter::Step;
  |     ^^^^^^^^^^^^^^^

error: use of unstable library feature 'step_trait': likely to be replaced by finer-grained traits (see issue #42168)
 --> src/main.rs:4:32
  |
4 |     type Index: Sized + Copy + Step;
  |                                ^^^^

Am I missing something or is it just not possible to do so right now?

like image 800
larvyde Avatar asked Dec 18 '22 01:12

larvyde


1 Answers

If you want to require that a Range<T> can be iterated over, just use that as your trait bound:

trait Bounded {
    type Index: Sized + Copy;
    fn bounds(&self) -> (Self::Index, Self::Index);
}

fn iterate<T>(it: &T)
where
    T: Bounded,
    std::ops::Range<T::Index>: IntoIterator,
{
    let (low, high) = it.bounds();
    for i in low..high {}
}

fn main() {}
like image 166
Shepmaster Avatar answered Jan 12 '23 17:01

Shepmaster