title: Lifetimes in HashMap where key refers to value
body: <p>I'm relatively new to Rust.  I want to write a function that will create a HashMap from a collection given a closure that generates a key from a value, e.g.</p>
  
  <pre><code>[derive(Debug)]
  struct Foo {
      id: u32,
      name: String,
  }
  let foos = vec![
      Foo { id: 1, name: "Bill".to_string() },
      Foo { id: 2, name: "Mary".to_string() },
  ];
  println!("{:?}", foos);
  println!("{:?}", map_by(foos.iter(), |f|  f.id));  // borrow  the Foos
  println!("{:?}", map_by(foos.iter(), |f| &amp;f.name));          // borrow
  println!("{:?}", map_by(foos.iter(), |f|  f.name.as_str())); // borrow
  println!("{:?}", map_by(foos,        |f|  f.id));  // consume the Foos
  </code></pre>
  
  <p>I wrote this, and it works for the above uses:</p>
  
  <pre><code>fn map_by&lt;I,K,V&gt;(iterable: I, f: impl Fn(&amp;V) -&gt; K) -&gt; HashMap&lt;K,V&gt;
  where I: IntoIterator&lt;Item = V&gt;,
        K: Eq + Hash
  {
      iterable.into_iter().map(|v| (f(&amp;v), v)).collect()
  }
  
  [Foo { id: 1, name: "Bill" }, Foo { id: 2, name: "Mary" }]
  {1: Foo { id: 1, name: "Bill" }, 2: Foo { id: 2, name: "Mary" }}
  {"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
  {"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
  {2: Foo { id: 2, name: "Mary" }, 1: Foo { id: 1, name: "Bill" }}
  </code></pre>
  
  <p>Great!  But it doesn't work when I let the HashMap OWN the values when the keys refer to them:</p>
  
  <pre><code>println!("{:?}", map_by(foos,        |f| f.name.as_str()));
  
  error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  </code></pre>
  
  <p>And unfortunately the error message melted my brain.  I tried specifying that the key and value have the same lifetime, but it didn't help.  <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=b9b79f36c46b214c0c17b9140b105de5" rel="nofollow noreferrer">Here it is in a playground</a>.  What is the compiler trying to tell me, and what am I doing wrong?  Surely if this can work when we borrow the values, it can work when we own them.</p>