Hi, I ran into a lifetime issue while implementing Iterator
for my type. I narrowed it down to the following MWE:
pub struct Foo ([u32; 10]);
struct FooIter<'a> {
idx: usize,
x: &'a Foo,
}
impl<'a> Iterator for FooIter<'a> {
type Item = &'a u32;
fn next<'b>(&'b mut self) -> Option<Self::Item> {
let reference: &'a Foo = self.x;
todo!()
}
}
struct FooIterMut<'a> {
idx: usize,
x: &'a mut Foo,
}
impl<'a> Iterator for FooIterMut<'a> {
type Item = &'a mut u32;
fn next<'b>(&'b mut self) -> Option<Self::Item> {
let reference: &'a mut Foo = self.x;
todo!()
}
}
Why does FooIter::next()
compile, but FooIterMut::next()
doesn't?
My reasoning is this: FooIter*
contain a lifetime parameter 'a
. In next
, I am taking a mut ref (of lifetime 'b
) to FooIter*
, therefore this 'b
must life at least as long as 'a
. Therefore, I can get a reference with lifetime 'a
to self.x
from a reference to self
with lifetime 'b
. Also, since the argument is a mut ref, I have an exclusive borrow and so there shouldn't be a problem to get mut references to its fields.
Where am I going wrong? And why does this compile (as expected to me) for the &
case but not for the &mut
case? Thanks!