为什么 for 循环不要求迭代器是可变的?
Why does a for loop not require the iterator to be mutable?
我不了解 Rust 迭代器的可变性。为了弄清楚,我有以下内容:
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);
}
}
非常简单,我有一个自定义迭代器,我 return 使用 fibonacci
。现在,当我创建它时,f
变量是不可变的。 for
循环中发生了什么使它起作用? for 循环不就是可变地使用 f
吗?
Didn't the for loop just use f
mutably?
没有。 take
returns a new iterator. But even then, for
is syntactic sugar。您的代码被转换为
let f: Fibonacci = fibonacci();
{
let result = match IntoIterator::into_iter(f.take(5)) {
mut iter => {
loop {
match iter.next() {
Some(i) => {
println!("{}", i);
}
None => break,
}
}
}
};
result
}
由于 IntoIterator
,我们永远不必变异 f
或 f.take(5)
,而只需 into_iter
.
的结果
我不了解 Rust 迭代器的可变性。为了弄清楚,我有以下内容:
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);
}
}
非常简单,我有一个自定义迭代器,我 return 使用 fibonacci
。现在,当我创建它时,f
变量是不可变的。 for
循环中发生了什么使它起作用? for 循环不就是可变地使用 f
吗?
Didn't the for loop just use
f
mutably?
没有。 take
returns a new iterator. But even then, for
is syntactic sugar。您的代码被转换为
let f: Fibonacci = fibonacci();
{
let result = match IntoIterator::into_iter(f.take(5)) {
mut iter => {
loop {
match iter.next() {
Some(i) => {
println!("{}", i);
}
None => break,
}
}
}
};
result
}
由于 IntoIterator
,我们永远不必变异 f
或 f.take(5)
,而只需 into_iter
.