为什么 for 循环不需要可变迭代器? [英] Why does a for loop not require a mutable iterator?
问题描述
如果我想手动使用迭代器,它必须是可变的:
If I want to consume an iterator by hand, it has to be mutable:
let test = vec![1, 2, 3];
let mut test_mut = test.iter();
while let Some(val) = test_mut.next() {
println!("{:?}", val);
}
但我可以用 for
循环愉快地使用它,即使它是不可变的.
But I can happily consume it with a for
loop, even if it's immutable.
let test = vec![1, 2, 3];
let test_imm = test.iter();
for val in test_imm {
println!("{:?}", val);
}
我认为这是可行的,因为 test_imm
被移动到 for 循环的块中,所以 test_imm
不能被任何外部块使用more 并且(从外部块的角度来看)在 for 循环之前是不可变的,然后它是不可访问的,所以没关系.
I think this works because test_imm
is moved into the for loop's block, so test_imm
can't be used by the outer block any more and is (from the point of view of the outer block) immutable up until the for loop, and then it's inaccessible, so it's okay.
是吗?还有什么需要解释的吗?
Is that right? Is there more to be explained?
推荐答案
完全正确.由于它已移至 for 循环,因此 for 循环现在拥有它并且可以用它做任何它想做的事情,包括使其"可变.考虑这个类似的例子,尽管 xs
是不可变的,但我们似乎在改变它,但实际上是因为我们正在移动它,所以新的所有者可以随意使用它,包括重新-将其绑定为可变的:
That's exactly right. Since it's moved to the for loop, the for loop now owns it and can do whatever it wants with it, including "making it" mutable. Consider this analogous example, where we appear to be mutating xs
despite it being immutable, but really it's because we're moving it, so the new owner is free to do with it whatever it wants, including re-binding it as mutable:
let xs: Vec<i32> = vec![1, 2, 3];
fn append(v: Vec<i32>, x: i32) -> Vec<i32> {
let mut my_v = v;
my_v.push(x);
my_v
}
let appended = append(xs, 4);
请注意,可以使用 mut
参数方便语法使函数更短:
Note that the function can be made shorter using the mut
parameter convenience syntax:
fn append(mut v: Vec<i32>, x: i32) -> Vec<i32> {
v.push(x);
v
}
这在在iter
模块的文档.
This is more or less explained in the iter
module's documentation.
这篇关于为什么 for 循环不需要可变迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!