Zero
Zero

Reputation: 1899

Rust can't figure out the type of a borrowed value

type NodePointer<T> = Option<Rc<RefCell<Node<T>>>>;

#[derive(Debug)]
struct Node<T> {
    val: T,
    next: NodePointer<T>
}

pub struct LinkedList<T> {
    head: NodePointer<T>,
    tail: NodePointer<T>,
    length: u32
}

impl <T: Display> Display for LinkedList<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut current = self.head.clone();
        
        while let Some(node_rc) = current {
            let node = node_rc.borrow_mut();
            write!(f, "{} ", node.val)?;
            current = node.next.clone();
        }
        Ok(())
    }
}

I was trying to make a LinkedList to just learn Rust and here I am stuck in a rather weird error. In the fmt function using node_rc.borrow() gives me

consider giving `node` an explicit type, where the type for type parameter `Borrowed` is specified: `: &Borrowed`

However using borrow_mut instead of borrow isn't causing this same error, why?

Upvotes: -1

Views: 37

Answers (1)

Zero
Zero

Reputation: 1899

I found a fix, it was because rust-analyzer was importing borrow from borrow::Borrow instead of cell::RefCell. It wasn't a bug related to how Rust works. Just wrong imports. Removing use std::borrow::Borrow fixed this.

Upvotes: 0

Related Questions