title: How do I update a variable in a loop to a reference to a value created inside the loop?
body: <p>I want to enter a loop with a variable <code>n</code> which is borrowed by the function. At each step, <code>n</code> takes a new value; when exiting the loop, the job is done, with the help of other variables, and <code>n</code> will <em>never</em> be used again.</p>
  
  <p>If I don't use references, I have something like this:</p>
  
  <pre><code>fn test(n: Thing) -&gt; usize {
      // stuff
      let mut n = n;
      for i in 1..10 {
          let (q, m) = n.do_something(...);
          n = m;
          // stuff with x
      }
      x
  }
  </code></pre>
  
  <p><code>x</code> is the result of some computation with <code>q</code> and <code>m</code> but it is an <code>usize</code> type and I didn't encounter any issue in this part of the code. I didn't test this code, but this is the idea. I could make code written like this work.</p>
  
  <p>Since I want to do it with a reference; I tried to write:</p>
  
  <pre><code>fn test(n: &amp;Thing) -&gt; usize {
      // stuff
      let mut n = n;
      for i in 1..10 {
          let (q, m) = (*n).do_something(...);
          n = &amp;m;
          // stuff with x
      }
      x
  }
  </code></pre>
  
  <p>Now the code will not compile because <code>m</code> has a shorter lifetime than <code>n</code>. I tried to make it work by doing some tricky things or by cloning things, but this can't be the right way. In C, the code would work because we don't care about what <code>n</code> is pointing to when exiting the loop since <code>n</code> isn't used after the loop. I perfectly understand that this is where Rust and C differ, but I am pretty sure a clean way of doing it in Rust exists.</p>
  
  <p>Consider my question as very general; I am not asking for some <em>ad-hoc</em> solution for a specific problem.</p>