when tried impl a double linked list in rust, i found below unexpected error
if let Some(link) = self.tail.take() {
let x = link.borrow_mut();
link.borrow_mut().next = Some(node.clone());
} else { ... }
here link is inferred to be Rc<RefCell<Node<..>>>
and compiler says:
Cannot borrow immutable local variable
link
as mutable.
After tried, I guess when use std::borrow::BorrowMut
, the error occurs.
// compiles
fn test1() {
let a = Rc::new(RefCell::new(1));
let b = RefCell::new(1);
b.borrow_mut();
a.borrow_mut();
}
// doesn't compile
fn test2() {
use std::borrow::BorrowMut; // inserted this import!
let a = Rc::new(RefCell::new(1));
let b = RefCell::new(1);
b.borrow_mut();
a.borrow_mut();
}
here test2()
fails to be compiled. I wanna know why it works this way.