title: How do I write an iterator that returns references to itself?
body: <p>I am having trouble expressing the lifetime of the return value of an <code>Iterator</code> implementation. How can I compile this code without changing the return value of the iterator? I'd like it to return a vector of references.</p>
  
  <p>It is obvious that I am not using the lifetime parameter correctly but after trying various ways I just gave up, I have no idea what to do with it.</p>
  
  <pre><code>use std::iter::Iterator;
  
  struct PermutationIterator&lt;T&gt; {
      vs: Vec&lt;Vec&lt;T&gt;&gt;,
      is: Vec&lt;usize&gt;,
  }
  
  impl&lt;T&gt; PermutationIterator&lt;T&gt; {
      fn new() -&gt; PermutationIterator&lt;T&gt; {
          PermutationIterator {
              vs: vec![],
              is: vec![],
          }
      }
  
      fn add(&amp;mut self, v: Vec&lt;T&gt;) {
          self.vs.push(v);
          self.is.push(0);
      }
  }
  
  impl&lt;T&gt; Iterator for PermutationIterator&lt;T&gt; {
      type Item = Vec&lt;&amp;'a T&gt;;
      fn next(&amp;mut self) -&gt; Option&lt;Vec&lt;&amp;T&gt;&gt; {
          'outer: loop {
              for i in 0..self.vs.len() {
                  if self.is[i] &gt;= self.vs[i].len() {
                      if i == 0 {
                          return None; // we are done
                      }
                      self.is[i] = 0;
                      self.is[i - 1] += 1;
                      continue 'outer;
                  }
              }
  
              let mut result = vec![];
  
              for i in 0..self.vs.len() {
                  let index = self.is[i];
                  result.push(self.vs[i].get(index).unwrap());
              }
  
              *self.is.last_mut().unwrap() += 1;
  
              return Some(result);
          }
      }
  }
  
  fn main() {
      let v1: Vec&lt;_&gt; = (1..3).collect();
      let v2: Vec&lt;_&gt; = (3..5).collect();
      let v3: Vec&lt;_&gt; = (1..6).collect();
  
      let mut i = PermutationIterator::new();
      i.add(v1);
      i.add(v2);
      i.add(v3);
  
      loop {
          match i.next() {
              Some(v) =&gt; {
                  println!("{:?}", v);
              }
              None =&gt; {
                  break;
              }
          }
      }
  }
  </code></pre>
  
  <p>(<a href="https://play.rust-lang.org/?gist=5043a6c209abf337921630e8064ad4a7&amp;version=stable" rel="noreferrer">Playground link</a>)</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0261]: use of undeclared lifetime name `'a`
    --&gt; src/main.rs:23:22
     |
  23 |     type Item = Vec&lt;&amp;'a T&gt;;
     |                      ^^ undeclared lifetime
  </code></pre>