struct Counter { count: u32, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option { self.count += 1; if self.count < 6 { Some(self.count) } else { None } } } fn main() { let mut my_counter = Counter::new(); println!("{}", my_counter.next().unwrap()) } #[test] fn counter_next_test() { let mut counter = Counter::new(); assert_eq!(counter.next(), Some(1)); assert_eq!(counter.next(), Some(2)); assert_eq!(counter.next(), Some(3)); assert_eq!(counter.next(), Some(4)); assert_eq!(counter.next(), Some(5)); assert_eq!(counter.next(), None); } /** * 出于某种原因我们希望获取 Counter 实例产生的值, * 将这些值与另一个 Counter 实例在省略了第一个值之后产生的值配对, * 将每一对值相乘,只保留那些可以被三整除的结果,然后将所有保留的结果相加 */ #[test] fn using_other_iterator_methods() { let counter = Counter::new(); let other_counter = Counter::new(); let res: u32 = counter .zip(other_counter.skip(1)) .map(|(s, o)| { println!("({s}, {o})"); s * o }) .filter(|v| { println!("{v}"); v % 3 == 0 }) .sum(); println!("res: {res}"); assert_eq!(res, 5); }