I ran into a lifetime issue i don't understand which I've reduced to this minimalish example:
#![allow(dead_code)]
struct ComplexOuterObject(i32);
impl ComplexOuterObject {
fn complex_objects(&self) -> ComplexObjectIter {
ComplexObjectIter {
x: self,
count: 0,
obj: None,
}
}
}
struct ComplexInnerObject<'a>(i32, &'a ComplexOuterObject);
struct ComplexObjectIter<'a> {
x: &'a ComplexOuterObject,
count: i32,
obj: Option<ComplexInnerObject<'a>>,
}
impl<'a> Iterator for ComplexObjectIter<'a> {
type Item = &'a ComplexInnerObject<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.obj = Some(ComplexInnerObject(self.x.0 + self.count, self.x));
self.count += 1;
if self.count >= 3 {
None
} else {
self.obj.as_ref()
}
}
}
fn main() {
let v = vec![0, 1, 2];
let outer = ComplexOuterObject(0);
v.iter().zip(outer.complex_objects());
}
Error:
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:32:13
|
23 | impl<'a> Iterator for ComplexObjectIter<'a> {
| -- lifetime `'a` defined here
...
26 | fn next(&mut self) -> Option<Self::Item> {
| - let's call the lifetime of this reference `'1`
...
32 | self.obj.as_ref()
| ^^^^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
error: could not compile `playground` due to previous error
rustc complains that the returned reference has the lifetime associated with &mut self
, rather than &'a
. However, both lifetimes are bound by the lifetime of ComplexOuterObject
, references to which are what drive the need for having a lifetime annotation in the first place. AFAICT there is no safety issue?