pub struct Stack<T> {
head: Link<T>,
}
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct Iter<'a, T>(&'a Link<T>);
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.0.as_ref().map(|node| {
self.0 = &node.next;
&node.elem
})
}
}
pub struct IterMut<'a, T>(&'a mut Link<T>);
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.0.as_mut().map(|node| {
self.0 = &mut node.next;
&mut node.elem
})
}
}
Why is there a lifetime issue when using &mut
(line 31) but not with &
(line 18)? Is there a way to make this work? One way is to change IterMut itself: Final Code. But I want to know how the &mut lifetimes are working different from the & lifetimes for exactly similar code.