title: Lifetime Confusion for iterator
body: <p>I am new to Rust and currently have been following <a href="https://rust-unofficial.github.io/too-many-lists/second-iter-mut.html" rel="nofollow noreferrer">Learning Rust With Entirely Too Many Linked Lists</a> examples. Before section <code>IterMut</code> everything makes sense to me. Yet when implementing <code>IterMut</code>(in a differrnt way from the tutorial), I got totally confused by lifetime mechanism in Rust. Here is the case, first I'd just define the stack to be implemented:</p>
  <pre class="lang-rust prettyprint-override"><code>pub struct List&lt;T&gt; {
      head: Link&lt;T&gt;,
  }
  
  type Link&lt;T&gt; = Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;;
  
  struct Node&lt;T&gt; {
      elem: T,
      next: Link&lt;T&gt;,
  }
  </code></pre>
  <p>Ok then when I try to implement iterator in the following way:</p>
  <pre class="lang-rust prettyprint-override"><code>pub struct IterMut&lt;'a, T&gt;{
      this: &amp;'a mut Link&lt;T&gt;
  }
  
  impl&lt;T&gt; List&lt;T&gt; {
      pub fn iter_mut(&amp;mut self) -&gt; IterMut&lt;T&gt; {
          IterMut {
              this: &amp;mut self.head
          }
      }
  }
  
  impl&lt;'a, T&gt; Iterator for IterMut&lt;'a, T&gt;{
      type Item = &amp;'a mut T;
      fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
          if let Some(node) = self.this {
              Some(&amp;mut node.elem)
          } else {
              None
          }
      }
  }
  </code></pre>
  <p>It won't compile, the result says:</p>
  <pre><code>error: lifetime may not live long enough
  impl&lt;'a, T&gt; Iterator for IterMut&lt;'a, T&gt;{
      -- lifetime `'a` defined here
      type Item = &amp;'a mut T;
      fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
              - let's call the lifetime of this reference `'1`
          if let Some(node) = self.this {
              Some(&amp;mut node.elem)
              ^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'a`
  </code></pre>
  <p>Originally, I implement function <code>next</code> in this way, using <code>as_mut</code> and <code>map</code>:</p>
  <pre class="lang-rust prettyprint-override"><code>// function body in the fn next
  self.this.as_mut().map(|node|{
      self.this = &amp;mut node.next;
      &amp;mut node.elem
  })
  </code></pre>
  <p>This also triggers compilation error (incompatible lifetime).</p>
  <p>Therefore I wonder what is going on here, shouldn't <code>self</code> in <code>fn next</code> have the same lifetime as <code>IterMut</code> ('a)? And is there any workaround for this situation?</p>