Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over mutable elements inside another mutable iteration over the same elements?

I have an array of Elements and I want to iterate over it to do some stuff, then iterate over all Elements inside the loop to do something. There is a relation between elements so I want to iterate to all other elements to check something. The elements are mutable references for reasons. It's a bit broad, but I'm trying to be general (maybe I should not).

struct Element;

impl Element {
    fn do_something(&self, _e: &Element) {}
}

fn main() {
    let mut elements = [Element, Element, Element, Element];

    for e in &mut elements {
        // Do stuff...

        for f in &mut elements {
            e.do_something(f);
        }
    }
}

As expected, I got this error:

error[E0499]: cannot borrow `elements` as mutable more than once at a time
  --> src/main.rs:13:18
   |
10 |     for e in &mut elements {
   |              -------------
   |              |
   |              first mutable borrow occurs here
   |              first borrow later used here
...
13 |         for f in &mut elements {
   |                  ^^^^^^^^^^^^^ second mutable borrow occurs here

I know it's a normal behavior in Rust, but what's the recommended way to avoid this error? Should I copy the elements first? Forget about loops and iterate in a different way? Learn about code design?

Is there a Rusty way to do this?

like image 960
rap-2-h Avatar asked Jan 30 '23 16:01

rap-2-h


2 Answers

You can use indexed iteration instead of iterating with iterators. Then, inside the inner loop, you can use split_at_mut to obtain two mutable references into the same slice.

for i in 0..elements.len() {
    for j in 0..elements.len() {
        let (e, f) = if i < j {
            // `i` is in the left half
            let (left, right) = elements.split_at_mut(j);
            (&mut left[i], &mut right[0])
        } else if i == j {
            // cannot obtain two mutable references to the
            // same element
            continue;
        } else {
            // `i` is in the right half
            let (left, right) = elements.split_at_mut(i);
            (&mut right[0], &mut left[j])
        };
        e.do_something(f);
    }
}
like image 51
oli_obk Avatar answered Feb 03 '23 14:02

oli_obk


You cannot do this, period. The rules of references state, emphasis mine:

At any given time, you can have either one mutable reference or any number of immutable references

On the very first iteration, you are trying to get two mutable references to the first element in the array. This must be disallowed.


Your method doesn't require mutable references at all (fn do_something(&self, e: &Element) {}), so the simplest thing is to just switch to immutable iterators:

for e in &elements {
    for f in &elements {
        e.doSomething(f);
    }
}

If you truly do need to perform mutation inside the loop, you will also need to switch to interior mutability. This shifts the enforcement of the rules from compile time to run time, so you will now get a panic when you try to get two mutable references to the same item at the same time:

use std::cell::RefCell;

struct Element;

impl Element {
    fn do_something(&mut self, _e: &mut Element) {}
}

fn main() {
    let mut elements = [
        RefCell::new(Element),
        RefCell::new(Element),
        RefCell::new(Element),
        RefCell::new(Element),
    ];

    for e in &elements {
        for f in &elements {
            // Note that this will panic as both `e` and `f` 
            // are the same value to start with
            let mut e = e.borrow_mut();
            let mut f = f.borrow_mut();
            e.do_something(&mut f);
        }
    }
}
like image 41
Shepmaster Avatar answered Feb 03 '23 12:02

Shepmaster