title: How do I implement a container with support for a mutable iterator?
body: <p>I want to design a toy container class with support for mutable iterators, but I'm having trouble sorting out the lifetimes of the iterator and its reference to the container.</p>
  
  <p>I've tried to create a minimal non-compiling example:</p>
  
  <pre><code>struct Payload {
      value: i32,
  }
  
  struct Container {
      val: Payload,
  }
  
  struct IterMut&lt;'a&gt; {
      cont: &amp;'a mut Container,
      cnt: i32,
  }
  
  impl&lt;'a&gt; Container {
      fn new() -&gt; Container {
          Container { val: Payload { value: 42 } }
      }
      fn iter_mut(&amp;'a mut self) -&gt; IterMut&lt;'a&gt; {
          IterMut {
              cont: self,
              cnt: 10,
          }
      }
  }
  
  impl&lt;'a&gt; Iterator for IterMut&lt;'a&gt; {
      type Item = &amp;'a mut Payload;
  
      fn next&lt;'b&gt;(&amp;'b mut self) -&gt; Option&lt;Self::Item&gt; {
          self.cnt -= 1;
  
          if self.cnt &lt; 0 {
              return None;
          } else {
              Some(&amp;mut self.cont.val)
          }
      }
  }
  
  fn main() {
      let mut cont = Container::new();
  
      let mut it = cont.iter_mut();
      it.next();
  }
  </code></pre>
  
  <p>The above is intended to implement a real stupid container that returns the same item 10 times when iterated over using <code>iter_mut()</code>. </p>
  
  <p>I can't figure out how to implement <code>Iterator::next</code>.</p>
  
  <p>I did manage to write a regular function that implements the same semantics as what I want for <code>next</code>:</p>
  
  <pre><code>fn manual_next&lt;'a, 'b&gt;(i: &amp;'a mut IterMut&lt;'b&gt;) -&gt; Option&lt;&amp;'a mut Payload&gt; {
      i.cnt -= 1;
  
      if i.cnt &lt; 0 {
          return None;
      } else {
          Some(&amp;mut i.cont.val)
      }
  }
  </code></pre>
  
  <p>This doesn't help, because I can't manage to adapt it to implement <code>Iterator::next</code>, and without implementing <code>Iterator</code>, my container can't be iterated over in for-loops, which I want.</p>