遍历一系列通用类型

Iterating over a range of generic type

我有一个特点

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

我想获取 bounds 内的所有 Indexes:

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

这行不通,因为没有类型 T 可以超过 "ranged" 的限制,而且编译器也这么说:

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>`

我尝试将 Step 添加到 Index

use std::iter::Step;

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

但显然它不稳定:

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;
  |                                ^^^^

我是不是遗漏了什么,或者现在不能这样做?

一般来说,num 箱子很有帮助。

extern crate num;

use num::{Num, One};
use std::fmt::Debug;

fn iterate<T>(low: T, high: T)
where
    T: Num + One + PartialOrd + Copy + Clone + Debug,
{
    let one = T::one();
    let mut i = low;
    loop {
        if i > high {
            break;
        }
        println!("{:?}", i);

        i = i + one;
    }
}

fn main() {
    iterate(0i32, 10i32);
    iterate(5u8, 7u8);
    iterate(0f64, 10f64);
}

如果你想要求 Range<T> 可以迭代,只需将其用作你的特征边界:

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() {}