iter::from_fn

版本新特性 / Rust 1.34

// *** 以前 ***
// 由闭包生成的序列过去需要用 impl Iterator 为它单独定义一个类型
struct Countdown(u32);

impl Iterator for Countdown {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        if self.0 == 0 { return None; }
        self.0 -= 1;
        Some(self.0)
    }
}

// *** 在 1.34 版本中 ***
let mut n = 3;
let countdown = std::iter::from_fn(move || {
    if n == 0 { return None; }
    n -= 1;
    Some(n)
});

println!("{:?}", countdown.collect::<Vec<_>>());   // [2, 1, 0]