27

I tried:

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?

I get errors like:

  • 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
Stargateur
  • 24,473
  • 8
  • 65
  • 91
ZisIsNotZis
  • 1,570
  • 1
  • 13
  • 30

1 Answers1

38

You may want to re-read The Rust Programming Language, specifically the sections on:

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 add 50 to each element.

let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50;
}

Listing 8-9: Iterating over mutable references to elements in a vector

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.

In addition, you can call the iter_mut method:

let mut v = vec![100, 32, 57];
for i in v.iter_mut() {
    *i += 50;
}

See also:


Note that your variable is not a vector. It is an array.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks. I totally missed the no bracket version for `for mut x in &(mut vec)` – ZisIsNotZis Sep 21 '16 at 20:09
  • If you already have a mutable slice like `v: &mut [u32]` as a function arg, `for i in v { *i += 50; }` works the same as `v.iter_mut()`. (I don't know if there's any subtle difference, but it compiled the same way.) – Peter Cordes May 26 '22 at 01:58
  • I undertand what mutability is, I don't understand why a variable should be mutable as a loop argument, when it's actually immutable (read: not changed, only read). – flm Jan 21 '23 at 22:52
  • @flm mutability in Rust is hierarchical — in order to change a value inside the `Vec` you also need to be able to change the `Vec` itself. The compiler doesn't know / expose to the user the fact that changing one element of a `Vec` doesn't require changing the data of the `Vec` itself. – Shepmaster Jan 24 '23 at 19:00
  • @Shepmaster, okay I see. `i` - is an array item and it changed inside the loop, that's why original array `v` marked as mutable, because its value is changed inside this loop. – flm Jan 27 '23 at 15:47