N00b question: how do I modify a vector after iterating over it?

Trying the follow listing but it does not compile...

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

    for x in a{
        print!("{},",x);
    }

    a[0] += 1;
1 Like

This will consume the iterator, it's like calling into_iter:

for x in a {
  /// ...
}

However, if you do the same thing on a reference a won't move:

for x in &a {
  /// ...
}
2 Likes

So the error message we get is:

  Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of moved value: `a`
   --> src/main.rs:8:5
    |
2   |     let mut a = vec![1,2,3];
    |         ----- move occurs because `a` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3   | 
4   |     for x in a{
    |              -
    |              |
    |              `a` moved due to this implicit call to `.into_iter()`
    |              help: consider borrowing to avoid moving into the for loop: `&a`
...
8   |     a[0] += 1;
    |     ^ value borrowed here after move
    |
note: this function consumes the receiver `self` by taking ownership of it, which moves `a`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

If you read carefully, it actually tells you what went wrong and how to fix it:

`a` moved due to this implicit call to `.into_iter()`
    |              help: consider borrowing to avoid moving into the for loop: `&a`
...

What we need to do is take a reference to a when we loop over it, so that when we print we don't steal all of the values out of a by moving them:

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

    for x in &a {
        print!("{},",x);
    }

    a[0] += 1;
9 Likes