title: HashMap borrow issue when trying to implement find or insert
body: <p>I tried to implement own analogue of <code>find_or_insert</code> method that looks like this:</p>
  
  <pre><code>use std::collections::HashMap;
  
  pub struct SomeManager {
      next: i32,
      types: HashMap&lt;i32, i32&gt;,
  }
  
  impl SomeManager {
      pub fn get_type&lt;'a&gt;(&amp;'a mut self, k: i32) -&gt; &amp;'a i32 {
          match self.types.get(&amp;k) {
              Some(ref x) =&gt; return *x,
              None =&gt; {
                  self.types.insert(k, self.next);
                  self.next += 1;
                  return self.types.get(&amp;k).unwrap();
              }
          }
      }
  }
  
  fn main() {}
  </code></pre>
  
  <p>Error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0502]: cannot borrow `self.types` as mutable because it is also borrowed as immutable
    --&gt; src/main.rs:13:17
     |
  10 |         match self.types.get(&amp;k) {
     |               ---------- immutable borrow occurs here
  ...
  13 |                 self.types.insert(k, self.next);
     |                 ^^^^^^^^^^ mutable borrow occurs here
  ...
  18 |     }
     |     - immutable borrow ends here
  </code></pre>
  
  <p>I know that there are some standard methods that implement this functionality, but I want this method to be as light as possible - it will be called very-very often and almost all of the time the values will already exist.</p>
  
  <p>As I understand it, when we call <code>self.types.get</code> we borrow it to scope of <strong>match</strong> statement, so we can't call <code>self.types.insert</code> here. I have tried to move methods from <strong>None</strong> branch out of <strong>match</strong> statement, but it also fails. </p>
  
  <p>The only working solution that I found requires invoking <code>get</code> twice:</p>
  
  <pre><code>pub fn get_type&lt;'a&gt;(&amp;'a mut self, k: i32) -&gt; &amp;'a i32 {
      let is_none = match self.types.get(&amp;k) {
          Some(ref x) =&gt; false,
          None =&gt; true,
      };
      if is_none {
          self.types.insert(k, self.next);
          self.next += 1;
      }
      self.types.get(&amp;k).unwrap()
  }
  </code></pre>
  
  <p>How can I work around such situations?</p>