Borrowing in nested loops

How should I refactor the code?

struct Polygons;

fn work(list: &mut Vec<Vec<Polygons>>, index: usize) {
    for target in &mut list[index] {
        for prev in &list[index - 1] {
            *target = todo(target, prev);
        }
    }
}

// only take shared borrows
fn todo(_target: &Polygons, _prev: &Polygons) -> Polygons {
    todo!()
}

error[E0502]: cannot borrow `*list` as immutable because it is also borrowed as mutable
 --> src/lib.rs:5:22
  |
4 |     for target in &mut list[index] {
  |                   ----------------
  |                   |    |
  |                   |    mutable borrow occurs here
  |                   mutable borrow later used here
5 |         for prev in &list[index - 1] {
  |                      ^^^^ immutable borrow occurs here
fn work(list: &mut Vec<Vec<Polygons>>, index: usize) {
    let (before, these) = match &mut list[index - 1 ..] {
        [before, these, ..] => (before, these),
        _ => panic!("Index out of range"),
    };

    for target in these {
        for prev in &*before {
            *target = todo(target, prev);
        }
    }
}
2 Likes

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.