11
Peek
peek returns a reference to the head element without removing it: Option<&T>. The fight here is going from &Option<Box<Node<T>>> to Option<&T> without moving anything. That's what as_ref and as_deref exist for.
-
Option::as_refconverts&Option<T>intoOption<&T>. Thenmaplets us reach into theBoxand grab&node.elem.Box<T>derefs toT, so&node.elemis&T.impl<T> List<T> { pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| &node.elem) } } -
as_derefis the convenience version that combinesas_refwith aDeref. OnOption<Box<Node<T>>>,as_deref()gives youOption<&Node<T>>directly — useful when you want to skip past theBoxindirection in one call. We'll lean on this shape in the iterators.// equivalent shapes: let a: Option<&Node<T>> = self.head.as_ref().map(|b| &**b); let b: Option<&Node<T>> = self.head.as_deref(); -
peek_mutis the mirror image:as_mutonOption, thenmapto a&mut node.elem. The signature returnsOption<&mut T>, which the caller can use to overwrite the head element in place.impl<T> List<T> { pub fn peek_mut(&mut self) -> Option<&mut T> { self.head.as_mut().map(|node| &mut node.elem) } } let mut list: List<i32> = List::new(); list.push(1); if let Some(v) = list.peek_mut() { *v = 42; } assert_eq!(list.peek(), Some(&42));