Hello,
I am scratching my head with this error. I have a mutable reference to a vector, which I want to loop over multiple times, but I cannot do it because my reference seems to itself be moved when I loop over it the first time.
With the following (simplified) code :
fn main() {
let mut values = vec![10, 11, 12];
let v = &mut values;
let mut max = 0;
//for n in &mut values {
for n in v {
max = std::cmp::max(max, *n);
}
println!("max is {}", max);
println!("Converting to percentages of maximum value...");
//for n in &mut values {
for n in v {
*n = 100 * (*n) / max;
}
println!("values: {:#?}", values);
}
I get the following error :
error[E0382]: use of moved value: `v`
--> src/main.rs:15:14
|
3 | let v = &mut values;
| - move occurs because `v` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
...
8 | for n in v {
| -
| |
| `v` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&v`
...
15 | for n in v {
| ^ value used here after move
|
Now if I follow the advice of the compiler and replace v
with &v
in the first for
, I get this new error :
error[E0277]: `&&mut Vec<{integer}>` is not an iterator
--> src/main.rs:8:14
|
8 | for n in &v {
| ^^ `&&mut Vec<{integer}>` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&&mut Vec<{integer}>`
= note: required by `into_iter`
Also, if I replace both for n in v
by the (currently commented out) for n in &mut values
, everything works as I expect.
(But I cannot do that because in my real world code I only have the mutable reference v
.)
Could someone explain to me what is happening here ? It looks like the v
reference is itself moved on the first for
and not « inside » v
anymore, and that does not happen when creating the reference within the for n in &mut values
(presumably because it then creates two new references ?), but I am not sure I understand it fully.
What is the correct way to solve that ? And what exactly is happening ?
Thank you.