Iterating over a range of generic type

余生长醉 提交于 2019-12-05 22:01:16

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

To do this kind of thing generically the num crate is helpful.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!