13
Iter
Iter walks the list without consuming it, yielding &T. The iterator doesn't own anything — it holds a reference to the current node. That reference has to live as long as the borrow of the list it came from, so a lifetime appears in the type for the first time.
-
Iter<'a, T>carriesOption<&'a Node<T>>.'ais the lifetime of the borrow of the list — the iterator can't outlive the list it's walking. The constructor takes&'a selfand usesas_derefto peel theBoxoff the head.pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } impl<T> List<T> { pub fn iter(&self) -> Iter<'_, T> { Iter { next: self.head.as_deref() } } } - Each
nextreturns the current node's element and advances the cursor by walkingnode.next.as_deref()to the nextOption<&Node<T>>. Shared references can be copied freely, so this is a one-line state update.impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { self.next.map(|node| { self.next = node.next.as_deref(); &node.elem }) } } - The
'_initer(&self) -> Iter<'_, T>is the elided lifetime — the compiler infers it from&self. Spelling it out as<'a>(&'a self) -> Iter<'a, T>is equivalent.let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut it = list.iter(); assert_eq!(it.next(), Some(&3)); assert_eq!(it.next(), Some(&2)); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), None); // list is still alive here.