title: How to return a reference to a sub-value of a value that is under a mutex?
body: <p>I have a structure that looks somewhat like this:</p>
  
  <pre><code>pub struct MyStruct {
      data: Arc&lt;Mutex&lt;HashMap&lt;i32, Vec&lt;i32&gt;&gt;&gt;&gt;,
  }
  </code></pre>
  
  <p>I can easily get a lock on the mutex and query the underlying <code>HashMap</code>:</p>
  
  <pre><code>let d = s.data.lock().unwrap();
  let v = d.get(&amp;1).unwrap();
  println!("{:?}", v);
  </code></pre>
  
  <p>Now I want to make a method to encapsulate the querying, so I write something like this:</p>
  
  <pre><code>impl MyStruct {
      pub fn get_data_for(&amp;self, i: &amp;i32) -&gt; &amp;Vec&lt;i32&gt; {
          let d = self.data.lock().unwrap();
          d.get(i).unwrap()
      }
  }
  </code></pre>
  
  <p>This fails to compile because I'm trying to return a reference to the data under a <code>Mutex</code>:</p>
  
  <pre class="lang-none prettyprint-override"><code>error: `d` does not live long enough
    --&gt; &lt;anon&gt;:30:9
     |
  30 |         d.get(i).unwrap()
     |         ^
     |
  note: reference must be valid for the anonymous lifetime #1 defined on the block at 28:53...
    --&gt; &lt;anon&gt;:28:54
     |
  28 |     pub fn get_data_for(&amp;self, i: &amp;i32) -&gt; &amp;Vec&lt;i32&gt; {
     |                                                      ^
  note: ...but borrowed value is only valid for the block suffix following statement 0 at 29:42
    --&gt; &lt;anon&gt;:29:43
     |
  29 |         let d = self.data.lock().unwrap();
     |                                           ^
  </code></pre>
  
  <p>I can fix it by wrapping the <code>HashMap</code> values in an <code>Arc</code>, but it looks ugly (<code>Arc</code> in <code>Arc</code>) and complicates the code:</p>
  
  <pre><code>pub struct MyStruct {
      data: Arc&lt;Mutex&lt;HashMap&lt;i32, Arc&lt;Vec&lt;i32&gt;&gt;&gt;&gt;&gt;,
  }
  </code></pre>
  
  <p>What is the best way to approach this? Is it possible to make a method that does what I want, without modifying the data structure?</p>
  
  <p><a href="https://play.rust-lang.org/?gist=1b612a0968b0666f5fc414c395715d0a&amp;version=stable&amp;backtrace=0" rel="noreferrer">Full example code</a>.</p>