title: Are there any differences between these two drop implementations for a singly-linked list
body: <p>I'm working through <em><a href="https://rust-unofficial.github.io/too-many-lists/first-drop.html" rel="nofollow noreferrer">Learning Rust with Entirely Too Many Linked Lists</a></em> and had a question about the drop implementation for the initial linked list from that book. The linked list is composed of a stack allocated link, which is either empty or points to a heap allocated Node with some associated data.</p>
  <pre class="lang-rust prettyprint-override"><code>struct List {
      head: Link,
  }
  
  enum Link {
      Empty,
      More(Box&lt;Node&gt;),
  }
  
  struct Node {
      data: i32,
      next: Link,
  }
  </code></pre>
  <p>The implementation of the drop trait given in the book uses <code>std::mem::replace</code> to take ownership of the nodes in the list.</p>
  <pre class="lang-rust prettyprint-override"><code>// Copied from the book, omitting comments
  impl Drop for List {
      fn drop(&amp;mut self) {
          let mut cur_link = mem::replace(&amp;mut self.head, Link::Empty);
          while let Link::More(mut boxed_node) = cur_link {
              cur_link = mem::replace(&amp;mut boxed_node.next, Link::Empty);
          }
      }
  }
  </code></pre>
  <p>I'm confused why the book is using <code>mem::replace</code> to take ownership of the next pointer of the node. It seems like we already have owndership of <code>boxed_node</code> from the <code>while let</code> line and we can just set cur_link to <code>node.next</code> instead of using <code>mem::replace</code>.</p>
  <p>I wrote this alternative implementation which compiles just fine. I'm wondering if there is any difference between the two drop methods.</p>
  <pre class="lang-rust prettyprint-override"><code>impl Drop for List {
      fn drop(&amp;mut self) {
          let mut link = mem::replace(&amp;mut self.head, Link::Empty);
          while let Link::More(node) = link {
              link = node.next;
          }
      }
  }
  </code></pre>