如何确定返回对成员变量的引用的函数的生存期?只要该结构还活着,该引用就有效。
这是一个可能需要这样做的示例:
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)
}
}
我已经尽可能地将解决方案与this question相匹配,但是我想遍历&T
而不是Vec<&T>
。