[英]Why does the compiler not complain that an iterator moved to a for loop is immutable?
I am reading the second edition of the Rust Book and I found the following sample in the iterators section: 我正在阅读Rust Book的第二版,我在迭代器部分找到了以下示例:
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("Got: {}", val);
}
Why does the compiler not complain that v1_iter
is immutable? 为什么编译器不抱怨
v1_iter
是不可变的? The book says the for loop took ownership of v1_iter
and made it mutable behind the scenes, but can you convert an immutable variable to mutable? 该书说for循环取得了
v1_iter
所有权,并使其在幕后变得可变,但是你可以将一个不可变变量转换为可变吗?
The book says the for loop took ownership of v1_iter and made it mutable behind the scenes,
该书说for循环取得了v1_iter的所有权,并使其在幕后变得可变,
Exactly, and one can make an even simpler example: 确切地说,人们可以做一个更简单的例子:
let v = vec![1,2,3];
let mut x = v;
x.push(0);
Note that v
and x
are separate variable bindings: for as long as the variable v
retained our 3-element vector, the contract of the variable was that the vector will not be mutated. 请注意,
v
和x
是单独的变量绑定:只要变量v
保留了我们的3元素向量,变量的约定就是向量不会被变异。 However, the vector was moved to x
, which declares that mutability is acceptable. 但是,向量被移动到
x
,这表明可变性是可接受的。 The same applies to function calls: 这同样适用于函数调用:
fn foo(mut x: Vec<i32>) {
x.push(0);
}
let v = vec![1,2,3];
foo(v);
This is safe because only one of the variables owns the vector at any point of its lifetime. 这是安全的,因为只有一个变量在其生命周期的任何一点拥有向量。 Once
v
was moved to x
, v
can no longer be used. 将
v
移动到x
,将无法再使用v
。 Likewise, in your code, v1_iter
can no longer be used after the for loop. 同样,在您的代码中,在for循环之后不能再使用
v1_iter
。
but can you convert an immutable variable to mutable?
但是你可以将不可变变量转换为可变吗?
Both snippets work because the value was moved to a new variable declared as mut
. 两个片段都有效,因为该值已移至声明为
mut
的新变量。 However, once a variable is declared as immutable (or mutable), that variable stays so for all of its lifetime, and that cannot be changed. 但是,一旦变量被声明为不可变(或可变),该变量在其所有生命周期内都保持不变,并且无法更改。 So the answer is no, but ownership semantics enable moving values across variables with different mutability guarantees.
所以答案是否定的,但所有权语义允许在具有不同可变性保证的变量之间移动值。
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.