rust 基础 —— iterator 迭代器

一、自定义迭代器

实现 Iterator trait 即可

pub struct Counter {
    pub count: usize,
}

impl Iterator for Counter {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;
        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}

  

233