【发布时间】:2015-03-31 06:23:23
【问题描述】:
我正在编写一个链表来了解 Rust 的生命周期、所有权和引用。我有以下代码:
pub struct LinkedList {
head: Option<Box<LinkedListNode>>,
}
pub struct LinkedListNode {
next: Option<Box<LinkedListNode>>,
}
impl LinkedList {
pub fn new() -> LinkedList {
LinkedList { head: None }
}
pub fn prepend_value(&mut self) {
let mut new_node = LinkedListNode { next: None };
match self.head {
Some(ref head) => new_node.next = Some(*head),
None => new_node.next = None,
};
self.head = Some(Box::new(new_node));
}
}
fn main() {}
但我收到以下编译错误:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:18:52
|
18 | Some(ref head) => new_node.next = Some(*head),
| ^^^^^ cannot move out of borrowed content
较新版本的 Rust 有一个稍微不同的错误:
error[E0507]: cannot move out of `*head` which is behind a shared reference
--> src/main.rs:18:52
|
18 | Some(ref head) => new_node.next = Some(*head),
| ^^^^^ move occurs because `*head` has type `std::boxed::Box<LinkedListNode>`, which does not implement the `Copy` trait
我认为head 节点当前必须由self 拥有,这是链表。当我将其分配给new_node.next 时,可能会发生所有权变更。
如果可能的话,我宁愿不克隆该值,因为这似乎很浪费。我不想只是在函数期间“借用”它。我真的很想转让它的所有权。
我该怎么做?
我已经看过cannot move out of borrowed content when unwrapping a member variable in a &mut self method 和Cannot move out of borrowed content / cannot move out of behind a shared reference。
我尝试按照其中一个问题中接受的答案中的建议删除匹配臂,并在创建新的 LinkedListNode 时定义 next,但我收到了相同的错误消息。
我已成功添加了一个 append 方法,该方法将 LinkedListNode 添加到列表末尾。
【问题讨论】:
标签: reference rust move-semantics borrow-checker