title: "cannot return value referencing temporary value" and interior mutability in Rust
body: <p>I have the following code in Rust:</p>
  <pre><code>pub struct RegExpFilter {
      ...
      regexp_data: RefCell&lt;Option&lt;RegexpData&gt;&gt;,
      ...
  }
  
  struct RegexpData {
      regexp: regex::Regex,
      string: String
  }
  
  ...
      pub fn is_regexp_compiled(&amp;self) -&gt; bool {
          self.regexp_data.borrow().is_some()
      }
  
      pub fn compile_regexp(&amp;self) -&gt; RegexpData {
          ...
      }
  
      fn regexp(&amp;self) -&gt; &amp;regex::Regex {
          if !self.is_regexp_compiled() { // lazy computation that mutates the struct
              self.regexp_data.replace(Some(self.compile_regexp()));
          }
          &amp;self.regexp_data.borrow().as_ref().unwrap().regexp
      }
      
      pub fn matches(&amp;self, location: &amp;str) -&gt; bool {
           self.regexp().find(location)
      }
  </code></pre>
  <p>regexp is calculated lazily, capturing <code>&amp;mut self</code> i undesired so <code>RefCell</code> is used.</p>
  <p>I'm getting the following message:</p>
  <pre><code>               &amp;self.regexp_data.borrow().as_ref().unwrap().regexp
      |          ^-------------------------^^^^^^^^^^^^^^^^^^^^^^^^^
      |          ||
      |          |temporary value created here
      |          returns a value referencing data owned by the current function
  </code></pre>
  <p>The compiler message seems to be clear: <code>Ref</code> is temporarily created by <code>borrow()</code> and returned outside. However i believe <code>Option</code> (<code>self.regexp_data</code>) is owned by <code>RefCell</code> which is owned by the struct itself, so it should be fine to use it internally (since the function is not <code>pub</code>).</p>
  <p>I've also tried the following (and it fails with the same message)</p>
  <pre><code>    fn regexp(&amp;self) -&gt; impl Deref&lt;Target = regex::Regex&gt; + '_ {
          if !self.is_regexp_compiled() {
              self.regexp_data.replace(Some(self.compile_regexp()));
          }
          Ref::map(self.regexp_data.borrow(), |it| &amp;it.unwrap().regexp)
      }
  </code></pre>
  <p>How can i solve it?</p>