title: How do you create an iterator using a closure in rust?
body: <p>I naively tried to do this:</p>
  
  <pre><code>struct Foo&lt;'a, S: Send, T:Send&gt; {
      next_:Box&lt;Fn&lt;(&amp;'a mut S,), Option&lt;T&gt;&gt; + Send&gt;,
      state:S
  }
  
  impl&lt;'a, S: Send, T: Send&gt; Iterator&lt;T&gt; for Foo&lt;'a, S, T&gt; {
      fn next(&amp;mut self) -&gt; Option&lt;T&gt; {
          return self.next_.call((&amp;mut self.state,));
      }
  }
  </code></pre>
  
  <p>To create an iterator I could send to a task easily using a closure.</p>
  
  <p>However, it generates the dreaded lifetime mismatch error:</p>
  
  <pre><code>&lt;anon&gt;:8:33: 8:48 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  &lt;anon&gt;:8         return self.next_.call((&amp;mut self.state,));
                                           ^~~~~~~~~~~~~~~
  &lt;anon&gt;:7:5: 9:6 help: consider using an explicit lifetime parameter as shown: fn next(&amp;'a mut self) -&gt; Option&lt;T&gt;
  &lt;anon&gt;:7     fn next(&amp;mut self) -&gt; Option&lt;T&gt; {
  &lt;anon&gt;:8         return self.next_.call((&amp;mut self.state,));
  &lt;anon&gt;:9     }
  error: aborting due to previous error
  playpen: application terminated with error code 101
  </code></pre>
  
  <p>I don't understand the error. </p>
  
  <p>The closure should take an argument with the lifetime 'a, which is the lifetime of the struct. </p>
  
  <p>The state is owned by the struct, so it has a lifetime of 'a.</p>
  
  <p>Using next_.call((&amp;mut self.state,)) doesn't invoke a task; it should only be for the duration of the call(), which as far as I can tell should be valid.</p>
  
  <p>So the mismatch here is between the lifetime on self in next(), and the 'a in call... but I don't see why it would not be 'a.</p>
  
  <p>What's the right way to fix the code above?</p>
  
  <p>Is there a better approach to take to do this?</p>
  
  <p>playpen: <a href="http://is.gd/hyNi0S" rel="nofollow">http://is.gd/hyNi0S</a></p>