Dereferencing boxed struct and moving its field ca

2020-02-07 06:45发布

问题:

Dereferencing a boxed struct and moving its field causes it to be moved, but doing it in another way works just fine. I don't understand the difference between these two pop functions. How does one fail when the other one doesn't?

pub struct Stack<T> {
    head: Option<Box<Node<T>>>,
    len: usize,
}
struct Node<T> {
    element: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Stack<T> {
    pub fn pop(&mut self) -> Option<T> {
        self.head.take().map(|boxed_node| {
            let node = *boxed_node;
            self.head = node.next;
            node.element
        })
    }

    pub fn pop_causes_error(&mut self) -> Option<T> {
        self.head.take().map(|boxed_node| {
            self.head = (*boxed_node).next;
            (*boxed_node).element
        })
    }
}
error[E0382]: use of moved value: `boxed_node`
  --> src/main.rs:22:13
   |
21 |             self.head = (*boxed_node).next;
   |                         ------------------ value moved here
22 |             (*boxed_node).element
   |             ^^^^^^^^^^^^^^^^^^^^^ value used here after move
   |
   = note: move occurs because `boxed_node.next` has type `std::option::Option<std::boxed::Box<Node<T>>>`, which does not implement the `Copy` trait

回答1:

You can only move out of a box once:

struct S;

fn main() {
    let x = Box::new(S);
    let val: S = *x;
    let val2: S = *x; // <-- use of moved value: `*x`
}

In the first function, you moved the value out of the box and assigned it to the node variable. This allows you to move different fields out of it. Even if one field is moved, other fields are still available. Equivalent to this:

struct S1 {
    a: S2,
    b: S2,
}
struct S2;

fn main() {
    let x = Box::new(S1 { a: S2, b: S2 });

    let tmp: S1 = *x;
    let a = tmp.a;
    let b = tmp.b;
}

In the second function, you move the value to the temporary (*boxed_node) and then move a field out of it. The temporary value is destroyed immediately after the end of the expression, along with its other fields. The box doesn't have the data anymore, and you don't have a variable to take the other field from. Equivalent to this:

struct S1 {
    a: S2,
    b: S2,
}
struct S2;

fn main() {
    let x = Box::new(S1 { a: S2, b: S2 });

    let tmp: S1 = *x;
    let a = tmp.a;

    let tmp: S1 = *x; // <-- use of moved value: `*x`
    let b = tmp.b;
}


回答2:

Some good news is that non-lexical lifetimes will allow your original code to work:

pub struct Stack<T> {
    head: Option<Box<Node<T>>>,
    len: usize,
}

struct Node<T> {
    element: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Stack<T> {
    pub fn pop_no_longer_causes_error(&mut self) -> Option<T> {
        self.head.take().map(|boxed_node| {
            self.head = (*boxed_node).next;
            (*boxed_node).element
        })
    }
}

NLL enhances the borrow checker to better track the moves of variables.



标签: rust