取消引用盒装结构并移动其字段会导致其被移动 [英] Dereferencing boxed struct and moving its field causes it to be moved

查看:33
本文介绍了取消引用盒装结构并移动其字段会导致其被移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取消引用一个装箱结构体并移动它的字段会导致它被移动,但以另一种方式做它就可以了.我不明白这两个 pop 函数之间的区别.当另一个没有失败时,一个如何失败?

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

推荐答案

一个盒子只能移出一次:

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`
}

在第一个函数中,您将值移出框外并将其分配给 node 变量.这允许您将不同的字段移出它.即使移动了一个字段,其他字段仍然可用.相当于:

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;
}

在第二个函数中,您将值移动到临时 (*boxed_node),然后从中移出一个字段.临时值在表达式结束后立即销毁,连同它的其他字段.该框不再有数据,并且您没有可以从中获取其他字段的变量.相当于:

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;
}

这篇关于取消引用盒装结构并移动其字段会导致其被移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆