title: How to circumvent "cannot borrow `*self` as mutable more than once at a time" in a performant way for agent based simulation?
body: <p>I would like to implement an agent-based simulation in Rust, but I run into the borrow checker.</p>
  <p>Agents should live in a mutable grid, carrying a state in each cell.
  Each agent carries some mutable state.
  Usually, I would implement a collection of agents, e.g. as a <code>HashMap</code> from grid position to agent.
  In a simulation step, I would iterate over all agents and then update the agent's state in dependence on its own state, the state of the grid at this position, and the state of other agents close by.</p>
  <p>A made-up example could look something like this:</p>
  <pre><code>use std::collections::HashMap;
  
  struct Agent { // each agent carries some state
      id: i64,
      state: i32,
  }
  
  struct CellState { // some state of a grid cell
      state: i64,
  }
  
  struct Chart {
      agents: HashMap&lt;usize, Agent&gt;,
      grid: Vec&lt;CellState&gt;,
  }
  
  impl Chart {
      fn new(size: usize) -&gt; Chart {
          let mut agents = HashMap::new(); // generate hash and populate with 2 agents
          agents.insert(10, Agent { id: 1, state: 1 });
          agents.insert(11, Agent { id: 2, state: 0 });
          let mut grid: Vec&lt;CellState&gt; = Vec::with_capacity(size);
  
          Chart {
              agents: agents,
              grid: grid,
          }
      }
  
      fn do_stuff(&amp;mut self, agent: &amp;mut Agent) {
          // here we want to update the state of agent,
          // based on the state of other agents in the grid
      }
  
      fn step_agents(&amp;mut self) {
          for (_, agent) in &amp;mut self.agents {
              self.do_stuff(agent);
          }
      }
  }
  
  fn main() {
      let mut ch = Chart::new(128);
      ch.step_agents();
  }
  </code></pre>
  <p>This code produces the error</p>
  <pre class="lang-none prettyprint-override"><code>error[E0499]: cannot borrow `*self` as mutable more than once at a time
    --&gt; src/main.rs:37:13
     |
  36 |         for (_, agent) in &amp;mut self.agents {
     |                           ----------------
     |                           |
     |                           first mutable borrow occurs here
     |                           first borrow later used here
  37 |             self.do_stuff(agent);
     |             ^^^^ second mutable borrow occurs here
  </code></pre>
  <p>I understand the error and why the Rust compiler has a problem. What I do not understand is how to circumvent this problem in a performant way.</p>
  <p>If I immutably borrow a reference to the agent, I cannot update its state. In a real example an agent would carry quite some state so cloning would not be cheap.</p>
  <p>What would be the idiomatic Rust way to implement this?</p>