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?