如何在 for 循环中进行可变借用? [英] How can I do a mutable borrow in a for loop?
问题描述
我试过了:
fn main() {
let mut vec = [1, 2, 3];
for mut x in &vec { *x = 3; }
for mut &x in &vec { x = 3; }
for mut *x in &vec { x = 3; }
for mut x in mut &vec { *x = 3; }
for mut x in &(mut vec) { *x = 3; }
}
这些都不起作用;我该怎么做?
None of these work; how should I do it?
我收到如下错误:
mut
必须附加到每个单独的绑定- 预期标识符,找到
*
- 预期表达式,找到关键字
mut
- 不能分配给
&
引用后面的*x
mut
must be attached to each individual binding- expected identifier, found
*
- expected expression, found keyword
mut
- cannot assign to
*x
which is behind a&
reference
推荐答案
您可能需要重新阅读 Rust 编程语言,特别是以下部分:
You may want to re-read The Rust Programming Language, specifically the sections on:
我们还可以遍历可变向量中每个元素的可变引用,以便对所有元素进行更改.示例 8-9 中的 for
循环会将 50
添加到每个元素.
We can also iterate over mutable references to each element in a mutable vector in order to make changes to all the elements. The
for
loop in Listing 8-9 will add50
to each element.
let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50;
}
示例 8-9:迭代对向量中元素的可变引用
Listing 8-9: Iterating over mutable references to elements in a vector
要改变可变引用所引用的值,我们必须使用解引用运算符(*
)来获取i
中的值,然后才能使用+=
运算符.
To change the value that the mutable reference refers to, we have to use the dereference operator (*
) to get to the value in i
before we can use the +=
operator.
另外,你可以调用iter_mut
方法:
In addition, you can call the iter_mut
method:
let mut v = vec![100, 32, 57];
for i in v.iter_mut() {
*i += 50;
}
另见:
请注意,您的变量不是向量.它是一个数组.
Note that your variable is not a vector. It is an array.
这篇关于如何在 for 循环中进行可变借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!