I'm writing a linked list to wrap my head around Rust lifetimes, ownership and references. I have the following code:
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() {}
But I am getting the following compilation error:
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
Newer versions of Rust have a slightly different error:
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
I'm thinking that the head
node must currently be owned by self
, which is the linked list. When I assign it to new_node.next
, there is probably a change of ownership that will happen.
I would rather not clone the value if possible as that seems wasteful. I don't want to just "borrow" it for the duration of the function. I really want to transfer its ownership.
How do I do that?
I have already looked at cannot move out of borrowed content when unwrapping a member variable in a &mut self method and Cannot move out of borrowed content / cannot move out of behind a shared reference.
I tried removing the match arm as suggested in the accepted answer in one of those questions and defining next
in the creation of the new LinkedListNode
, but I get the same error message.
I have successfully added an append
method which takes a LinkedListNode
to add to the end of the list.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…