← 中文资源

简体中文版本

自定义斐波那契迭代器

实现 Iterator trait 惰性产生斐波那契数列,展示如何在没有集合分配的情况下表达无穷序列。

阅读英文原文

实现说明

整个示例围绕函数 new、next、main组织。

使用要点

  • 演示输出是带标签的(even fibonacci sum =),每个操作都会留下自己的一行标注。
  • 运行整个文件:main 会依次驱动 new。

常见问题

运行「自定义斐波那契迭代器」会打印什么?

运行文件本身,even fibonacci sum = 这些前缀各对应一段演示逻辑。

主要签名是 fn new(remaining: usize) -> Self

核心语句

let sum: u64 = Fibonacci::new(10).filter(|n| n % 2 == 0).sum();
fn next(&mut self) -> Option<u64> {
    if self.remaining == 0 {
        return None;
    }
    let value = self.current;
    let following = self.current + self.next;
    self.current = self.next;
    self.next = following;
    self.remaining -= 1;
    Some(value)
}
fn new(remaining: usize) -> Self {
    Fibonacci { current: 0, next: 1, remaining }
}

代码示例

struct Fibonacci {
    current: u64,
    next: u64,
    remaining: usize,
}

impl Fibonacci {
    fn new(remaining: usize) -> Self {
        Fibonacci { current: 0, next: 1, remaining }
    }
}

impl Iterator for Fibonacci {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        if self.remaining == 0 {
            return None;
        }
        let value = self.current;
        let following = self.current + self.next;
        self.current = self.next;
        self.next = following;
        self.remaining -= 1;
        Some(value)
    }
}

fn main() {
    let sum: u64 = Fibonacci::new(10).filter(|n| n % 2 == 0).sum();
    println!("even fibonacci sum = {sum}");
}