0

How do I scope the lifetime for a function that returns a reference to a member variable? The reference will be valid as long as the struct is alive.

Here is an example where one might want this:

struct CountUpIter<'a, T> {
    output: &'a mut T,
}

fn next<'a, T>(selff: &'a mut CountUpIter<'a, T>) -> Option<&'a T> {
    Some(&selff.output)
}

// This does not work
// first, the lifetime cannot outlive the lifetime '_ as defined on the impl so that reference does not outlive borrowed content
// but, the lifetime must be valid for the lifetime 'a as defined on the impl
impl<'a, T> Iterator for CountUpIter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&self.output)
    }
}

// Neither does this. It fails with the same error
impl<'a, T> Iterator for &mut CountUpIter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&self.output)
    }
}

I have matched as much as possible the solution to this question, but I want to iterate over &T not Vec<&T>.

charmoniumQ
  • 5,214
  • 5
  • 33
  • 51
  • The proposed duplicate target is indeed applicable to owned values of a struct. Please read the answer again. What you can do is implement `Iterator` for a reference to `MyIter`, but not `MyIter` itself. – E_net4 May 03 '19 at 18:29
  • Do you mean `impl<'a, T> Iterator for & mut MyIter<'a, T>`? That has the same error. – charmoniumQ May 03 '19 at 19:20
  • You'll have to make a [MCVE] of that attempt, otherwise were unlikely to understand what went wrong. – E_net4 May 03 '19 at 19:23

0 Answers0