实现说明
整个示例围绕函数 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}");
}