我正在编写一个链表来理解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
。