title: How to iterate over mutable elements inside another mutable iteration over the same elements?
body: <p>I have an array of <code>Element</code>s and I want to iterate over it to do some stuff, then iterate over all <code>Element</code>s 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). </p>
  
  <pre><code>struct Element;
  
  impl Element {
      fn do_something(&amp;self, _e: &amp;Element) {}
  }
  
  fn main() {
      let mut elements = [Element, Element, Element, Element];
  
      for e in &amp;mut elements {
          // Do stuff...
  
          for f in &amp;mut elements {
              e.do_something(f);
          }
      }
  }
  </code></pre>
  
  <p>As expected, I got this error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0499]: cannot borrow `elements` as mutable more than once at a time
    --&gt; src/main.rs:13:18
     |
  10 |     for e in &amp;mut elements {
     |              -------------
     |              |
     |              first mutable borrow occurs here
     |              first borrow later used here
  ...
  13 |         for f in &amp;mut elements {
     |                  ^^^^^^^^^^^^^ second mutable borrow occurs here
  </code></pre>
  
  <p>I know it's <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references" rel="nofollow noreferrer">a normal behavior in Rust</a>, 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?</p>
  
  <p>Is there a Rusty way to do this?</p>