Why doesn't Option::map take ownership in a linked list implementation of Iterator::next?

78 Views Asked by At

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?

1

There are 1 best solutions below

0
On

Wouldn't that "steal" the value?

It would, except that Option<&T> is copyable. Thus self keeps one copy and map gets another.

need complete access to self

Since the value is copied into the map, there's no connection to the one in self. Thus the value in self can be replaced inside the closure.