title: How to lookup from and insert into a HashMap efficiently?
body: <p>I'd like to do the following:</p>
  
  <ul>
  <li>Lookup a <code>Vec</code> for a certain key, and store it for later use.</li>
  <li>If it doesn't exist, create an empty <code>Vec</code> for the key, but still keep it in the variable.</li>
  </ul>
  
  <p>How to do this efficiently? Naturally I thought I could use <code>match</code>:</p>
  
  <pre><code>use std::collections::HashMap;
  
  // This code doesn't compile.
  let mut map = HashMap::new();
  let key = "foo";
  let values: &amp;Vec&lt;isize&gt; = match map.get(key) {
      Some(v) =&gt; v,
      None =&gt; {
          let default: Vec&lt;isize&gt; = Vec::new();
          map.insert(key, default);
          &amp;default
      }
  };
  </code></pre>
  
  <p>When I tried it, it gave me errors like:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
    --&gt; src/main.rs:11:13
     |
  7  |     let values: &amp;Vec&lt;isize&gt; = match map.get(key) {
     |                                     --- immutable borrow occurs here
  ...
  11 |             map.insert(key, default);
     |             ^^^ mutable borrow occurs here
  ...
  15 | }
     | - immutable borrow ends here
  </code></pre>
  
  <p>I ended up with doing something like this, but I don't like the fact that it performs the lookup twice (<code>map.contains_key</code> and <code>map.get</code>):</p>
  
  <pre><code>// This code does compile.
  let mut map = HashMap::new();
  let key = "foo";
  if !map.contains_key(key) {
      let default: Vec&lt;isize&gt; = Vec::new();
      map.insert(key, default);
  }
  let values: &amp;Vec&lt;isize&gt; = match map.get(key) {
      Some(v) =&gt; v,
      None =&gt; {
          panic!("impossiburu!");
      }
  };
  </code></pre>
  
  <p>Is there a safe way to do this with just one <code>match</code>?</p>