title: Rust lifetimes - returning value from vector in RWLock in Arc
body: <p>I'm having a lot of trouble with lifetimes in relation to Arcs and RWLocks.</p>
  
  <pre class="lang-rust prettyprint-override"><code>struct ComponentContainer&lt;T&gt;{
      id_to_component: HashMap&lt;uint, uint&gt;,
      components: Arc&lt;RWLock&lt;~Vec&lt;T&gt;&gt;&gt;
  }
  </code></pre>
  
  <p>id_to_component is a map of component ids to an index into the Vec inside components.</p>
  
  <p>I've tried everything from the intuitive:</p>
  
  <pre class="lang-rust prettyprint-override"><code>impl&lt;T: Component&gt; ComponentContainer&lt;T&gt;{
      fn get&lt;'a&gt;(&amp;'a self, id: uint) -&gt; &amp;'a T {
          let idx = self.id_to_component.get(&amp;id);
          self.components.read().get(*idx)
      }
  }
  </code></pre>
  
  <p>To the extremely verbose (manually storing each reference):</p>
  
  <pre class="lang-rust prettyprint-override"><code>impl&lt;T: Component&gt; ComponentContainer&lt;T&gt; {
      fn get&lt;'a&gt;(&amp;'a self, id: uint) -&gt; &amp;'a T {
          let idx = self.id_to_component.get(&amp;id);
          let components: &amp;'a RWLock&lt;~Vec&lt;T&gt;&gt; = &amp;'a *self.components;
          let c: &amp;'a RWLock&lt;~Vec&lt;T&gt;&gt; = &amp;'a *components;
          let tmp: &amp;'a RWLockReadGuard&lt;'a, ~Vec&lt;T&gt;&gt; = &amp;'a c.read();
          let v: &amp;'a ~Vec&lt;T&gt; = &amp;'a **tmp;
          v.get(*idx)
      }
  }
  </code></pre>
  
  <p>With the verbose one, I end up getting the error:</p>
  
  <pre><code>error: borrowed value does not live long enough
  let tmp: &amp;'a RWLockReadGuard&lt;'a, ~Vec&lt;T&gt;&gt; = &amp;'a c.read();
                                              ^~~~~~~~~~~~
  </code></pre>
  
  <p>According to the source for RWLock.read(), the returned reference should have the specified lifetime, unless I'm reading it incorrectly.</p>
  
  <p>Edit: full rustc output for short version</p>
  
  <pre><code>test.rs:18:9: 18:31 error: borrowed value does not live long enough
  test.rs:18         self.components.read().get(*idx)
                     ^~~~~~~~~~~~~~~~~~~~~~
  test.rs:16:45: 19:6 note: reference must be valid for the lifetime &amp;'a  as defined on the block at 16:44...
  test.rs:16     fn get&lt;'a&gt;(&amp;'a self, id: uint) -&gt; &amp;'a T {
  test.rs:17         let idx = self.id_to_component.get(&amp;id);
  test.rs:18         self.components.read().get(*idx)
  test.rs:19     }
  test.rs:16:45: 19:6 note: ...but borrowed value is only valid for the block at 16:44
  test.rs:16     fn get&lt;'a&gt;(&amp;'a self, id: uint) -&gt; &amp;'a T {
  test.rs:17         let idx = self.id_to_component.get(&amp;id);
  test.rs:18         self.components.read().get(*idx)
  test.rs:19     }
  error: aborting due to previous error
  </code></pre>