title: What's the real meaning of the error "closure may outlive the current function"?
body: <p>I wrote the following to test closures:</p>
  
  <pre><code>fn main() {
      let captured_val = "a captured value".to_string();
      let closure_parameter = "a parameter value".to_string();
  
      let mut ct = ClosureTest {
          cls: |closure_parameter| &amp;captured_val,
      };
      println!("{}", (ct.cls)(&amp;closure_parameter));
  }
  
  struct ClosureTest&lt;T&gt;
  where
      T: FnMut(&amp;str) -&gt; &amp;str,
  {
      cls: T,
  }
  </code></pre>
  
  <p>I got the following compile error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0373]: closure may outlive the current function, but it borrows `captured_val`, which is owned by the current function
   --&gt; src/main.rs:6:14
    |
  6 |         cls: |closure_parameter| &amp;captured_val,
    |              ^^^^^^^^^^^^^^^^^^^  ------------ `captured_val` is borrowed here
    |              |
    |              may outlive borrowed value `captured_val`
  help: to force the closure to take ownership of `captured_val` (and any other referenced variables), use the `move` keyword
    |
  6 |         cls: move |closure_parameter| &amp;captured_val,
    |              ^^^^^^^^^^^^^^^^^^^^^^^^
  </code></pre>
  
  <p>I added a lifetime parameter to the struct and it compiled and worked fine:</p>
  
  <pre><code>struct ClosureTest&lt;'a, T&gt;
  where
      T: FnMut(&amp;str) -&gt; &amp;'a str,
  {
      cls: T,
  }
  </code></pre>
  
  <p>Both variables (<code>captured_val</code> and <code>closure_parameter</code>) are in the same scope, but it seems like that the compiler does not see them having the same lifetime without the lifetime parameter <code>'a</code> I added to <code>ClosureTest&lt;T&gt;</code>. Is this because of Rust's lifetime inference with closures?</p>
  
  <p>I don't understand the first line in the error message I got: </p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0373]: closure may outlive the current function, but it borrows `captured_val`, which is owned by the current function
  </code></pre>
  
  <p>How could the closure outlive the current function? The closure is defined just in the current function, so I think the closure is going to be gone at the end of the current function.</p>
  
  <p>What's the real meaning of the error message and why is it solved with adding the lifetime parameter as I did?</p>