0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
asp5
  • 371
  • 1
  • 10
  • Keep reading. The entire purpose of the code you are looking at is to present *many errors that you might see anyway*. The code you have pasted doesn't even compile. – Shepmaster Dec 24 '17 at 15:28

1 Answers1

1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366