0
我不明白Rust迭代器的可变性。为了揣摩出来,我有以下几点:为什么for循环不需要迭代器是可变的?
struct Fibonacci {
curr: u32,
next: u32,
}
impl Iterator for Fibonacci {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
Some(self.curr)
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
let f: Fibonacci = fibonacci();
for i in f.take(5) {
println!("> {}", i);
}
}
很简单,我有我返回使用fibonacci
自定义迭代器。现在,当我创建这个时,f
变量是不可变的。在for
循环中会发生什么? for循环不是可变地使用f
吗?