18

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
  • 20,831
  • 8
  • 51
  • 78
ZisIsNotZis
  • 1,380
  • 1
  • 11
  • 27

1 Answers1

29

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
  • 326,504
  • 69
  • 892
  • 1,159
  • 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