I am very new to Rust and I must be missing something crucial in borrowing/ownership rules because I can not understand why I'm getting an compile error. I'm working with your usual binary tree definitions:
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
and somewhere later do I call the following:
/*
* _t1 & _t2 are other TreeNodes.
* merge_trees() is defined as merge_trees(
* t1: Option<Rc<RefCell<TreeNode>>>,
* t2: Option<Rc<RefCell<TreeNode>>>,
* ) -> Option<Rc<RefCell<TreeNode>>>
*/
let mut head = TreeNode::new(_t1.borrow().val);
head.left = merge_trees(_t1.borrow().left, _t2.borrow().left);
I get the following error:
error[E0507]: cannot move out of dereference of `std::cell::Ref<'_, TreeNode>`
--> src/main.rs:234:29
|
234 | head.left = merge_trees(_t1.borrow().left, _t2.borrow().left);
| ^^^^^^^^^^^^^^^^^
| |
| move occurs because value has type `std::option::Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>`, which does not implement the `Copy` trait
| help: consider borrowing the `Option`'s content: `_t1.borrow().left.as_ref()`
I'm confused about the error; I can't really seem to parse the text properly. It seems that a move occurred and that's forbidden, but all I did was dereference my TreeNode struct. I realise that simply appending a .clone()
would fix this, but I don't know why dereferencing and passing in another TreeNode would be a problem.