gpt4 book ai didi

rust - 取消引用盒装结构并移动其字段会导致它被移动

转载 作者:行者123 更新时间:2023-11-29 08:20:28 27 4
gpt4 key购买 nike

取消引用一个盒装结构并移动它的字段会导致它被移动,但以另一种方式进行它就可以了。我不明白这两个 pop 函数之间的区别。为什么一个失败而另一个失败?

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

最佳答案

你只能离开盒子一次:

struct S;

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

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

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),然后从中移出一个字段。临时值在表达式结束后立即销毁,连同它的其他字段。该框不再有数据,您也没有可从中获取其他字段的变量。等同于:

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

关于rust - 取消引用盒装结构并移动其字段会导致它被移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com