通过获取所有权将不可变变量转换为可变变量
Converting a immutable variable to mutable by taking ownership
我正在经历 the Rust book from the official rust website and came across the following paragraph:
Note that we needed to make v1_iter
mutable: calling the next method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code consumes, or uses up, the iterator. Each call to next eats up an item from the iterator. We didn’t need to make v1_iter
mutable when we used a for loop because the loop took ownership of v1_iter
and made it mutable behind the scenes.
如果你注意到最后一行。它说 for 循环使可变变量在幕后不可变。如果可以的话,那我们程序员也可以这样做吗?
我知道这不安全,我们不应该那样做,但只是想知道这是否可能。
将不可变变量重新绑定到可变变量是完全没问题的,例如以下代码有效:
let x = 5;
let mut x = x;
在最后一条语句之后,我们可以改变 x
变量。其实想想,有两个变数,第一个是moved into latest。函数也可以做同样的事情:
fn f(mut x: i32) {
x += 1;
}
let y = 5;
f(y);
Rust 禁止的事情是将不可变引用更改为可变引用。这是一个重要的区别,因为与借来的相比,拥有的价值总是可以安全地改变。
我正在经历 the Rust book from the official rust website and came across the following paragraph:
Note that we needed to make
v1_iter
mutable: calling the next method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code consumes, or uses up, the iterator. Each call to next eats up an item from the iterator. We didn’t need to makev1_iter
mutable when we used a for loop because the loop took ownership ofv1_iter
and made it mutable behind the scenes.
如果你注意到最后一行。它说 for 循环使可变变量在幕后不可变。如果可以的话,那我们程序员也可以这样做吗?
我知道这不安全,我们不应该那样做,但只是想知道这是否可能。
将不可变变量重新绑定到可变变量是完全没问题的,例如以下代码有效:
let x = 5;
let mut x = x;
在最后一条语句之后,我们可以改变 x
变量。其实想想,有两个变数,第一个是moved into latest。函数也可以做同样的事情:
fn f(mut x: i32) {
x += 1;
}
let y = 5;
f(y);
Rust 禁止的事情是将不可变引用更改为可变引用。这是一个重要的区别,因为与借来的相比,拥有的价值总是可以安全地改变。