why RefCell borrowed value does not live long enough

80 Views Asked by At

I a newer to rust. I got an error in the function print. I already fix this error by using another kind of implementation. But I am still confused about this error. Why the compiler said borrowed value does not live long enough for node_ref. I think node_ref = cur_node.borrow(); already owned the Ref<>, why cur = node_ref.next.as_ref(); can't borrow it. As I know the node_ref will live long enough.

use std::cell::RefCell;
use std::rc::Rc;

struct DoubleLinkedListNode<T>
where
    T: std::fmt::Display,
{
    val: T,
    prev: Option<NodeRef<T>>,
    next: Option<NodeRef<T>>,
}
type NodeRef<T> = Rc<RefCell<DoubleLinkedListNode<T>>>;

impl<T> DoubleLinkedListNode<T>
where
    T: std::fmt::Display,
    T: std::default::Default,
{
    fn new(value: T) -> Self {
        DoubleLinkedListNode {
            val: value,
            prev: None,
            next: None,
        }
    }

    fn default() -> Self {
        Self {
            val: T::default(),
            prev: None,
            next: None,
        }
    }
}

struct DoubleLinkedList<T>
where
    T: std::fmt::Display,
{
    head: Option<NodeRef<T>>,
    tail: Option<NodeRef<T>>,
}

impl<T> DoubleLinkedList<T>
where
    T: std::fmt::Display,
    T: std::default::Default,
{
    fn new() -> Self {
        Self {
            head: None,
            tail: None,
        }
    }

    fn push_front(&mut self, value: T) {
        let new_node = Self::create_node(value);
        if let Some(old_head_node_ref) = &self.head {
            let new_head_node_ref = new_node;
            (*new_head_node_ref.borrow_mut()).next = Some(Rc::clone(old_head_node_ref));
            (*old_head_node_ref.borrow_mut()).prev = Some(Rc::clone(&new_head_node_ref));
            self.head = Some(Rc::clone(&new_head_node_ref));
        } else {
            self.head = Some(Rc::clone(&new_node));
            self.tail = Some(Rc::clone(&new_node));
        }
    }

    fn create_node(value: T) -> NodeRef<T> {
        Rc::new(RefCell::new(DoubleLinkedListNode::new(value)))
    }

    fn print(&self) {
        if self.head.is_none() {
            return;
        }
        let a = RefCell::new(DoubleLinkedListNode::<T>::default());
        let mut node_ref = a.borrow();
        let mut cur = self.head.as_ref();
        while let Some(cur_node) = cur {
            print!("{}, ", cur_node.borrow().val);
            node_ref = cur_node.borrow();
            cur = node_ref.next.as_ref();
        }
        println!();
    }
}
0

There are 0 best solutions below