为什么编译器不抱怨移动到 for 循环的迭代器是不可变的? [英] Why does the compiler not complain that an iterator moved to a for loop is immutable?

查看:57
本文介绍了为什么编译器不抱怨移动到 for 循环的迭代器是不可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Rust Book 的第二版,我在迭代器部分找到了以下示例:

I am reading the second edition of the Rust Book and I found the following sample in the iterators section:

let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();    
for val in v1_iter {
    println!("Got: {}", val);
}

为什么编译器不抱怨 v1_iter 是不可变的?这本书说 for 循环取得了 v1_iter 的所有权,并使其在幕后可变,但是你可以将不可变变量转换为可变变量吗?

Why does the compiler not complain that v1_iter is immutable? 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,

没错,我们可以举一个更简单的例子:

Exactly, and one can make an even simpler example:

let v = vec![1,2,3];
let mut x = v;
x.push(0);

注意 vx 是独立的变量绑定:只要变量 v 保留了我们的 3 元素向量,合约变量是向量不会发生突变.然而,向量被移动到 x,它声明可变性是可以接受的.这同样适用于函数调用:

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. However, the vector was moved to x, which declares that mutability is acceptable. The same applies to function calls:

fn foo(mut x: Vec<i32>) {
    x.push(0);
}

let v = vec![1,2,3];
foo(v);

这是安全的,因为只有一个变量在其生命周期的任何时刻拥有该向量.v 移到 x 后,就不能再使用 v.同样,在您的代码中,v1_iter 不能再在 for 循环之后使用.

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. Likewise, in your code, v1_iter can no longer be used after the for loop.

但是你能把不可变的变量转换成可变的吗?

but can you convert an immutable variable to mutable?

两个片段都有效,因为值被移动到一个声明为 mut 的新变量中.但是,一旦变量被声明为不可变(或可变),该变量将在其整个生命周期中保持不变,并且无法更改.所以答案是否定的,但所有权语义允许在具有不同可变性保证的变量之间移动值.

Both snippets work because the value was moved to a new variable declared as 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.

另见:

为什么 Rust 允许使用不可变绑定通过引用字段进行突变?

这篇关于为什么编译器不抱怨移动到 for 循环的迭代器是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆