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?