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>
.