title: Mixing mutable and immutable references to a HashMap
body: <p>I want to create a function which gets the value associated to a key in a hashtable, and, if such value does not exist, inserts an arbitrary value (let us say 0).</p>
  
  <pre><code>use std::collections::HashMap;
  
  fn get_or_insert(table: &amp;mut HashMap&lt;i32, i32&gt;, key: i32) -&gt; i32 {
      match table.get(&amp;key) {
          None =&gt; table.insert(key, 0).unwrap(),
          Some(v) =&gt; *v,
      }
  }
  </code></pre>
  
  <p>This code does not compile:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0502]: cannot borrow `*table` as mutable because it is also borrowed as immutable
   --&gt; src/main.rs:5:17
    |
  4 |     match table.get(&amp;key) {
    |           ----- immutable borrow occurs here
  5 |         None =&gt; table.insert(key, 0).unwrap(),
    |                 ^^^^^ mutable borrow occurs here
  6 |         Some(v) =&gt; *v,
  7 |     }
    |     - immutable borrow ends here
  </code></pre>
  
  <p>Indeed, <code>table</code> is mutably borrowed in the method <code>insert</code> whereas it is immutably borrowed in the method <code>get</code>.</p>
  
  <p>I can see no way to separate the mutable and immutable parts in this function.</p>