1

Consider the following examples taken from Learning Rust With Entirely Too Many Linked Lists

Example 1 rust playground

pub fn pop(&mut self) -> Option<i32> {
    match mem::replace(&mut self.head, Link::Empty) {
        Link::Empty => None,
        Link::More(boxed_node) => {
            let node = *boxed_node;
            self.head = node.next;
            //println!("{:?}", node); // Adding this line will induce the same error
            Some(node.elem)
        }
    }
}

Example 2 rust playground

pub fn pop(&mut self) -> Option<i32> {
    match mem::replace(&mut self.head, Link::Empty) {
        Link::Empty => None,
        Link::More(node) => {
            self.head = node.next;
            Some(node.elem)
        }
    }
}

Error from example 2

error[E0382]: use of moved value: `node`
  --> src/main.rs:42:20
   |
41 |                     self.head = node.next;
   |                                 --------- value moved here
42 |                     Some(node.elem)
   |                          ^^^^^^^^^ value used here after move
   |
   = note: move occurs because `node.next` has type `main::Link`, which does not implement the `Copy` trait

With the following types

struct Node {
    elem: i32,
    next: Link,
}

enum Link {
    Empty,
    More(Box<Node>),
}

In example 1, the content of the Box (e.g. struct) is first moved to node then part of the struct is moved to head

In example 2, part of the Box is moved to head.

Why doesn't example 1 have the same compiler error as example 2? Specifically, if I move part of a struct why doesn't it consume the entire struct?

Jal
  • 2,174
  • 1
  • 18
  • 37
  • Please review how to create a [MCVE] and then [edit] your question to include it. We cannot tell what types, and fields are present in the code. For example, you reference `self.head`, but nothing defines that. Ideally, produce something that reproduces your error on the [Rust Playground](https://play.rust-lang.org). There are [Rust-specific MCVE tips](//stackoverflow.com/tags/rust/info) as well. – Shepmaster Jun 20 '18 at 21:18
  • *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and **the shortest code necessary to reproduce it in the question itself**. Questions without a clear problem statement are not useful to other readers*; Linking to code is fine, but it *needs to be in the question*. – Shepmaster Jun 20 '18 at 21:57
  • I believe your question is answered by the answers of [How to bind multiple fields of a boxed struct without getting “use moved value” error?](https://stackoverflow.com/q/31391581/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 20 '18 at 21:58

0 Answers0