I'm trying to follow along Rust With Entirely Too Many Linked Lists.
type Link<T> = Option<Box<Node<T>>>;
pub struct List<T> {
head: Link<T>,
}
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct Iter<T> {
next: Option<&Node<T>>,
}
When implementing a iter
,
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
In the next
method, map
takes an Option
by value so it would need to
take self.next
which happens to be of type Option<&Node<T>>
by value. Wouldn't that "steal" the value?
Since the closure is a mutating one, shouldn't it need complete access to self
and this code shouldn't compile? Am I missing something here?
It would, except that
Option<&T>
is copyable. Thusself
keeps one copy andmap
gets another.Since the value is copied into the
map
, there's no connection to the one inself
. Thus the value inself
can be replaced inside the closure.