title: How do I use the Entry API with an expensive key that is only constructed if the Entry is Vacant?
body: <p>Is it possible to use the <a href="https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html" rel="noreferrer"><code>Entry</code></a> API to get a value by a <code>AsRef&lt;str&gt;</code>, but inserting it with <code>Into&lt;String&gt;</code>?</p>
  
  <p>This is the working example:</p>
  
  <pre class="lang-rust prettyprint-override"><code>use std::collections::hash_map::{Entry, HashMap};
  
  struct Foo;
  
  #[derive(Default)]
  struct Map {
      map: HashMap&lt;String, Foo&gt;,
  }
  
  impl Map {
      fn get(&amp;self, key: impl AsRef&lt;str&gt;) -&gt; &amp;Foo {
          self.map.get(key.as_ref()).unwrap()
      }
  
      fn create(&amp;mut self, key: impl Into&lt;String&gt;) -&gt; &amp;mut Foo {
          match self.map.entry(key.into()) {
              Entry::Vacant(entry) =&gt; entry.insert(Foo {}),
              _ =&gt; panic!(),
          }
      }
  
      fn get_or_create(&amp;mut self, key: impl Into&lt;String&gt;) -&gt; &amp;mut Foo {
          match self.map.entry(key.into()) {
              Entry::Vacant(entry) =&gt; entry.insert(Foo {}),
              Entry::Occupied(entry) =&gt; entry.into_mut(),
          }
      }
  }
  
  fn main() {
      let mut map = Map::default();
      map.get_or_create("bar");
      map.get_or_create("bar");
      assert_eq!(map.map.len(), 1);
  }
  </code></pre>
  
  <p><a href="https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=644a89e615a7503fc87742513b367816" rel="noreferrer">playground</a></p>
  
  <p>My problem is that in <code>get_or_create</code> a <code>String</code> will always be created, incurring unneeded memory allocation, even if it's not needed for an occupied entry. Is it possible to fix this in any way? Maybe in a neat way with <a href="https://doc.rust-lang.org/std/borrow/enum.Cow.html" rel="noreferrer"><code>Cow</code></a>?</p>