I was implementing an LinkedList to learn about smart pointers. This is the structures:
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
value: T,
next: Link<T>,
}
impl<T> Node<T> {
pub fn new(value: T) -> Rc<RefCell<Node<T>>> {
Rc::new(RefCell::new(Node { value, next: None }))
}
}
struct LinkedList<T> {
head: Link<T>,
}
While implementing the push method, I faced a problem with iteration over node.next
and I could solve this by doing the iteration with a loop, like this thread.
And before I move on to the next method, I've tried to implement with while let
, but doesn't work, and I don;t figure out why.
let mut curr = Rc::clone(head);
while let Some(ref boxed) = curr.borrow().next {
curr = Rc::clone(boxed);
}
// loop {
// let next = match curr.borrow().next {
// Some(ref boxed) => Rc::clone(boxed),
// None => break,
// };
// curr = next;
// }
curr.borrow_mut().next = Some(node);
The error occurs because the curr.borrow().next
is dropped when go to the next iteration?
Is there a way to implement that with while let
?