I am running some issues with RefCell that I don't really understand. Here is the code snippet.
struct TreeNode{
data: i32,
left: Option<Rc<RefCell<TreeNode>>>,
right: Option<Rc<RefCell<TreeNode>>>
}
let mut root = Rc::new(RefCell::new(TreeNode::new(1)));
let mut r_n = root.borrow().left.clone();
while let Some(current) = r_n {
root = current;
r_n = root.borrow().left.clone();
}
It works find and could compile. But when I want to succinct it to the following. It doesn't compile.
let mut root = Rc::new(RefCell::new(TreeNode::new(1)));
while let Some(inner) = root.borrow().left.clone() {
root = current;
}
It gives the following error. My understanding is that the borrow() method returns Ref<> which is not dropped before we try to borrow a mutable reference to root in the assignment. But I am not very clear why Ref<> is not dropped in the second case but is dropped in the first scenario. Is it related to the while let expression? Could anyone help me to understand it? I am new to Rust and trying to figure out if there is any rule that I am missing.
error[E0506]: cannot assign to `root` because it is borrowed
--> src/ch4.rs:141:13
|
139 | while let Some(current) = root.borrow().left.clone() {
| -------------
| |
| borrow of `root` occurs here
| a temporary with access to the borrow is created here ...
140 | let new = current.clone();
141 | root = new;
| ^^^^ assignment to borrowed `root` occurs here
142 | }
| - ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `Ref<'_, TreeNodeWithParent>`
|
= note: borrow occurs due to deref coercion to `RefCell<TreeNodeWithParent>`