问题
I tried:
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?
回答1:
You may want to re-read The Rust Programming Language section on mutability:
You can also create a reference to it, using
&x
, but if you want to use the reference to change it, you will need a mutable reference:let mut x = 5; let y = &mut x;
fn main() {
let mut array = [1, 2, 3];
for x in &mut array {
*x = 3;
}
}
See also:
- What's the difference in `mut` before a variable name and after the `:`?
Note that your variable is not a vector. It is an array.
来源:https://stackoverflow.com/questions/39622783/how-can-i-do-a-mutable-borrow-in-a-for-loop