gpt4 book ai didi

for-loop - 通过获取所有权将不可变变量转换为可变变量

转载 作者:行者123 更新时间:2023-12-03 11:34:07 24 4
gpt4 key购买 nike

我正在浏览 the Rust book来自 rust 官方网站,遇到了 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 循环使可变变量在幕后不可变。如果可以的话,那么作为程序员的我们是否也可以这样做呢?

就像我知道这不安全,我们不应该那样做,但只是想知道这是否可能。

最佳答案

将不可变变量重新绑定(bind)到可变变量是完全没问题的,例如以下代码有效:

let x = 5;
let mut x = x;

在最后一条语句之后,我们可以改变 x 变量。其实想想,有两个变数,第一个是到最新。函数也可以做同样的事情:

fn f(mut x: i32) {
x += 1;
}

let y = 5;
f(y);

Rust 中禁止的事情是将不可变引用更改为可变引用。这是一个重要的区别,因为与借来的值(value)相比,拥有的值(value)总是可以安全地改变。

关于for-loop - 通过获取所有权将不可变变量转换为可变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com