Converting a immutable variable to mutable by taking ownership
我正在浏览官方 rust 网站上的 Rust 书,并遇到了以下段落:
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 didna€?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 循环使可变变量在幕后不可变。如果这是可能的,那么作为程序员的我们是否可以这样做?
就像我知道这不安全,我们不应该那样做,只是想知道这是否可能。
将不可变变量重新绑定到可变变量是完全可以的,例如以下代码有效:
1 2 | let x = 5; let mut x = x; |
在最后一条语句之后,我们可以改变
1 2 3 4 5 6 | fn f(mut x: i32) { x += 1; } let y = 5; f(y); |
Rust 中禁止的事情是将不可变引用更改为可变引用。这是一个重要的区别,因为与借来的相比,拥有的价值总是可以安全地改变。