Deref and again create a &mut reference starting from a &mut reference

Looking at Vec implementation provided in The Rustonomicon book, i saw:

impl<T> Drop for IntoIter<T> {
    fn drop(&mut self) {
        for _ in &mut *self {}
    }
}

I cannot figure if Dereferencing self and producing again a &mut reference is really needed.
The code seems to work also without that extra op:

impl<T> Drop for IntoIter<T> {
    fn drop(&mut self) {
        for _ in self {}
    }
}

Are those code snippets equivalent?

1 Like

No, they aren't. Since mutable references aren't copiable, writing for _ in self moves the reference and makes it unusable. In contrast, a reborrow only "freezes" it temporarily (for the duration of the iteration), so you'll be able to access it later.

1 Like

Ok, right, semantically they are not equivalent. But for this case? After the iteration self is not used anymore.

Yeah. They're just using the IntoIterator implementation on &mut Vec<T> to remove all the items from the collection and let them be destroyed.

You could also implement it as while let Some(item) = self.pop() { drop(item); } or for item in self.drain(..) { drop(item); }[1], they're all different ways of achieving the same thing.


  1. The drop() call wasn't really necessary here. I just added it to make it explicit that we're only removing items so they can be destroyed. ↩ī¸Ž

1 Like