码迷,mamicode.com
首页 > 其他好文 > 详细

Rust中的迭代器

时间:2019-08-31 13:02:40      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:代码   self   str   else   new   mic   struct   elf   next   

和闭包一样,练代码

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::Item> {
        self.count += 1;

        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}

#[test]
fn using_other_iterator_trait_methods() {
    let sum: u32 = Counter::new().zip(Counter::new().skip(1))
                    .map(|(a, b)| a * b)
                    .filter(|x| x % 3 == 0)
                    .sum();
    assert_eq!(18, sum);
}

技术图片

Rust中的迭代器

标签:代码   self   str   else   new   mic   struct   elf   next   

原文地址:https://www.cnblogs.com/aguncn/p/11438455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!