How to iterate over mutable elements inside anothe

2019-07-04 13:18发布

问题:

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 doSomething(&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.doSomething(f);
        }
    }
}

As expected, I got this error:

cannot borrow elements as mutable more than once at a time

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?

DISCLAIMER: I know this is a common mistake and it may be answered elsewhere, but once again I'm lost. I did not find a relevant answer, maybe I don't know how to search. Sorry if it's a duplicate.

回答1:

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.doSomething(f);
    }
}


回答2:

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

At any given time, you can have either but not both of:

  • One mutable reference.
  • 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 doSomething(&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 if you try to get two mutable references to the same item at the same time.