1

I'm having some trouble understanding what's going on in this simple example:

let mut my_vec = vec![1, 2, 3, 4];

for v in &mut my_vec {
    *v += 1;
}

I would not expect this code to compile, as I'd assume that in the for loop, v would need to have been marked as &mut for it to work. But actually, marking it as &mut v makes the compilation fail. Why?!

My line of thought is as follows:

  1. I want to increment v by 1, so v needs to be both a reference and mutable, hence the variable declaration in the for loop should be &mut v;
  2. my_vec on the for-loop needs then to be marked as mut, as its values are going to be mutated, and as a reference, as we want to change the values of my_vec;
  3. my_vec then also needs to be marked as mut, otherwise no mutations can be performed on it.

In other words, if I had not run the code through a compiler, this is what I would have come up with:

let mut my_vec = vec![1, 2, 3, 4];

for &mut v in &mut my_vec {
    *v += 1;
}

Where am I failing?

devoured elysium
  • 101,373
  • 131
  • 340
  • 557
  • cause you are doing a pattern matching and so v become an integer and not anymore a reference to integer. for `x` in `y`, `x` is a pattern matching. – Stargateur Apr 13 '23 at 14:24

0 Answers0