rust iter3

struct CountdownIterator(i32);

impl Iterator for CountdownIterator {
    type Item = i32;
    fn next(&mut self) -> Option<Self::Item> {
        self.0 -= 1;
        if self.0 < 0 {
            None
        } else {
            Some(self.0)
        }
    }
}

struct Countdown(i32);

impl IntoIterator for Countdown {
    type Item = i32;
    type IntoIter = CountdownIterator;
    fn into_iter(self) -> Self::IntoIter {
        CountdownIterator(self.0)
    }
}

impl<'a> IntoIterator for &'a Countdown {
    type Item = i32;
    type IntoIter = CountdownIterator;
    fn into_iter(self) -> Self::IntoIter {
        CountdownIterator(self.0)
    }
}

impl<'a> IntoIterator for &'a mut Countdown {
    type Item = i32;
    type IntoIter = CountdownIterator;
    fn into_iter(self) -> Self::IntoIter {
        CountdownIterator(self.0)
    }
}

fn main() {
    let c = Countdown(10);
    for i in &c {
        for j in &c {
            println!("({0}, {1})", i, j)
        }
    }
}

  

posted @ 2022-07-28 12:26  CrossPython  阅读(15)  评论(0编辑  收藏  举报