I have the following data structure:
pub struct Node<T: Clone> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T>
where
T: Clone,
{
fn new(value: T) -> Self {
Node { value, next: None }
}
fn append(&mut self, value: T) {
let next = Some(Box::new(Node { value, next: None }));
if self.next.is_none() {
self.next = next;
return;
}
let mut temp = &mut self.next;
while let Some(node) = temp {
if node.next.is_some() {
temp = &mut node.next;
} else {
break;
}
}
// TODO: at this point, temp is the tail
}
}
Notice the commend at the end of the append
method. At this point, temp
points to the tail, but since it's an Option<Box<Node<T>>>
, I cannot access its next
property. When I try to use as_mut()
or replace()
or some related method from Option
, I get an error that temp
is already borrowed mutably.
Any idea on how to modify the Node<T>
within temp
?