为什么移动Box的子组件不会消耗整个Box,而移动struct的子组件却不会呢?

时间:2018-06-20 21:14:38

标签: rust

请考虑以下摘自Learning Rust With Entirely Too Many Linked Lists

的示例

示例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)
        }
    }
}

示例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)
        }
    }
}

示例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

具有以下类型

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

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

在示例1中,Box(例如struct)的内容首先移至node,然后将部分结构移至head

在示例2中,Box的一部分已移至head

为什么示例1与示例2没有相同的编译器错误?具体来说,如果我移动结构的一部分,为什么它不消耗整个结构?

0 个答案:

没有答案