// // // Iteration by value (simply empties the list as the caller now owns all values) // // pub struct IntoIter(List); impl Iterator for IntoIter { type Item = T; fn next(&mut self) -> Option { self.0.head.take().map(|node| { let node = *node; self.0.head = node.next; node.elem }) } } // // // Iteration by immutable reference // // pub struct Iter<'a, T: 'a> { next: Option<&'a Node>, } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option { self.next.take().map(|node| { self.next = node.next.as_ref().map(|node| &**node); &node.elem }) } } // // // Iteration by mutable reference // // pub struct IterMut<'a, T: 'a> { next: Option<&'a mut Node>, } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option { self.next.take().map(|node| { self.next = node.next.as_mut().map(|node| &mut **node); &mut node.elem }) } } // // // Methods implemented for List // // impl List { pub fn into_iter(self) -> IntoIter { IntoIter(self) } pub fn iter<'a>(&'a self) -> Iter<'a,T> { Iter { next: self.head.as_ref().map(|node| &**node) } } pub fn iter_mut(&mut self) -> IterMut { IterMut { next: self.head.as_mut().map(|node| &mut **node) } } }