title: Why are explicit lifetimes needed in Rust?
body: <p>I was reading the <a href="https://doc.rust-lang.org/book/first-edition/lifetimes.html" rel="noreferrer">lifetimes chapter</a> of the Rust book, and I came across this example for a named/explicit lifetime:</p>
  
  <pre><code>struct Foo&lt;'a&gt; {
      x: &amp;'a i32,
  }
  
  fn main() {
      let x;                    // -+ x goes into scope
                                //  |
      {                         //  |
          let y = &amp;5;           // ---+ y goes into scope
          let f = Foo { x: y }; // ---+ f goes into scope
          x = &amp;f.x;             //  | | error here
      }                         // ---+ f and y go out of scope
                                //  |
      println!("{}", x);        //  |
  }                             // -+ x goes out of scope
  </code></pre>
  
  <p>It's quite clear to me that the error being prevented by the compiler is the <em>use-after-free</em> of the reference assigned to <code>x</code>: after the inner scope is done, <code>f</code> and therefore <code>&amp;f.x</code> become invalid, and should not have been assigned to <code>x</code>.</p>
  
  <p>My issue is that the problem could have easily been analyzed away <em>without</em> using the <em>explicit</em> <code>'a</code> lifetime, for instance by inferring an illegal assignment of a reference to a wider scope (<code>x = &amp;f.x;</code>).</p>
  
  <p>In which cases are explicit lifetimes actually needed to prevent use-after-free (or some other class?) errors?</p>