0

I have a Combination struct and I need to implement Iterator for it. The trait requires defining the associated type Item and I need to define it as slice &[usize].

If I write this:

pub struct Combination {
    n: usize,
    k: usize,
    comb: Vec<usize>,
}

impl Iterator for Combination {
    type Item = &[usize];
    fn next(&mut self) -> Option<&[usize]> {
        // TODO
    }
}

The compiler says:

error[E0106]: missing lifetime specifier
 --> src/main.rs:9:17
  |
9 |     type Item = &[usize];
  |                 ^ expected lifetime parameter

If I specify a lifetime:

impl<'a> Iterator for Combination {
    type Item = &'a [usize];

This makes me add a lifetime specifier to Combination even if it doesn't need any lifetimes:

pub struct Combination<'a> {

Next, compiler gives the error that lifetime 'a is never used, and I have to add a PhantomData field:

pub struct Combination<'a> {
    n: usize,
    k: usize,
    comb: Vec<usize>,
    pd: std::marker::PhantomData<&'a [usize]>,
}

impl<'a> Iterator for Combination<'a> {
    type Item = &'a [usize];
    fn next(&mut self) -> Option<&[usize]> {
        // TODO
    }
}

It compiles, but looks like a kludge. Is there better solution?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mrbus2007
  • 197
  • 7
  • *but looks like a kludge* — it won't even compile if you try to implement the body, so this isn't even a solution. – Shepmaster Jun 26 '18 at 21:10
  • No errors related to lifetimes, I meant. `fn next`'s argument must be `&mut self`, not `&self`, and if I just return None it compiles. Apart from some warnings. – mrbus2007 Jun 26 '18 at 23:10
  • And `fn next`'s return type must be `Option<&'a [usize]>` of course – mrbus2007 Jun 26 '18 at 23:22
  • 1
    Yes, @Shepmaster, you're right, it doesn't compile when I try to return `Some(&self.comb)`. I need StreamingIterator or something else. – mrbus2007 Jun 27 '18 at 17:08

0 Answers0