0

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?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Kny
  • 26
  • 3
  • 1
    Before anything else, [don't learn by implementing a linked list in Rust](https://rust-unofficial.github.io/too-many-lists/). – Chayim Friedman May 21 '22 at 22:37
  • 1
    Why so many layers? Wouldn't `Option>>` be sufficient? What's the purpose of `Rc` and `RefCell`? – cdhowie May 21 '22 at 23:46
  • I think that is because i really dont understand ownership and borrowing. Made another list with the layers you've mentioned and it worked as expected. thank you for this comment, really made me think about why the use of things and I could use the statement ```while let Some()``` – Kny May 23 '22 at 12:29

0 Answers0