title: How to use a reference to the underlying data protected by a Arc<RwLock<T>>?
body: <p>Any reference obtained through the interior mutability pattern, be it <code>Rc&lt;RefCell&lt;T&gt;&gt;</code> or <code>Arc&lt;RwLock&lt;T&gt;&gt;</code>, will have to be dropped as the enclosing function returns. When you want to use this reference to return a reference to some data that this <code>RefCell</code> or <code>RwLock</code> protects, it is not allowed. </p>
  
  <p>I think it is right to NOT ALLOW it: because I am using interior mutability, any reference associated with the "interior" should be delegated to the runtime checker, and thus a pure reference as <code>&amp;T</code> should not be exposed to the outside. </p>
  
  <p>However, I could not figure out a good alternative that serves the same purpose, other than wrap the underlying data with <code>Rc&lt;RefCell&lt;T&gt;&gt;</code> as well. </p>
  
  <p>Code that demonstrates the issue: </p>
  
  <pre><code>use std::string::String;
  use std::sync::{Arc, RwLock};
  
  struct MyStruct {
      data: MyData,
  }
  
  struct MyData {
      val: String,
  }
  
  fn main() {
      let my_struct = MyStruct {
          data: MyData {
              val: String::from("hi"),
          },
      };
      let obj = Arc::new(RwLock::new(my_struct));
  
      let data = get_data_ref(&amp;obj);
      println!("{}", data);
  }
  
  fn get_data_ref(obj: &amp;Arc&lt;RwLock&lt;MyStruct&gt;&gt;) -&gt; &amp;String {
      let obj = Arc::clone(obj);
  
      let data = obj.read().unwrap(); //data is created
      data.get_data()
  } //data dropped here, thus lives not long enough.
  
  impl MyStruct {
      fn get_data(&amp;self) -&gt; &amp;String {
          self.data.get_val()
      }
  }
  
  impl MyData {
      fn get_val(&amp;self) -&gt; &amp;String {
          &amp;self.val
      }
  }
  </code></pre>
  
  <p>(<a href="https://play.rust-lang.org/?gist=315c85adae82ae12929e8873d32f91c9&amp;version=stable&amp;mode=debug&amp;edition=2015" rel="nofollow noreferrer">playground</a>)</p>