Cant borrow as mutable behind a `&` reference

I am trying to populate the data of a Struct within a Struct by passing it to a function to fill it with random data. However I cant get either the iterator correct or I am once again confused with the borrow checker. How can I resolve this or am I going about this the wrong way?

    let mut i = ships.iter();
    for mut ship in i {
        randomize_location(&mut rng, &mut ship.location);

I get:

error[E0596]: cannot borrow `ship.location` as mutable, as it is behind a `&` reference
  --> src/main.rs:81:38
   |
80 |     for mut ship in i {
   |                     - this iterator yields `&` references
81 |         randomize_location(&mut rng, &mut ship.location);
   |                                      ^^^^^^^^^^^^^^^^^^ `ship` is a `&` reference, so the data it refers to cannot be borrowed as mutable

iter generates an iterator of shared references; use iter_mut instead.

1 Like

If you use rust analyzer or any other IDE, you will see that ship is of type &Foo. So mut ship is mut &Foo, you can modify what ship points to, but not the value that ship points to. To modify the value, you need to get a mutable reference &mut Foo (or get the value Foo itself). In your case, what might be needed is iter_mut.

2 Likes

The iter_mut worked, and it solved another problem I was having with the iters. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.