Option `cannot move out of borrowed content`

When dealing with Leetcode problem Minimum Depth of Binary Tree, recursion method is pretty simple in C++ such as

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) {
            return 0;
        }
        if (!root->left && !root->right) {
            return 1;
        }
        if (!root->left) {
            return minDepth(root->right) + 1;
        }
        if (!root->right) {
            return minDepth(root->left) + 1;
        }
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
};

but when implementing it in Rust, I was stacked.
With Solution::min_depth(node.borrow().right) I got cannot move out of borrowed content error and don't know how to fix it. I'm confused with smart pointers and Option.

impl Solution {
    pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if let Some(node) = root {
            if node.borrow().left.is_none() && node.borrow().right.is_none() {
                return 1;
            }
            if node.borrow().left.is_none() {
                return Solution::min_depth(node.borrow().right) + 1;
            }
        }
        0
    }
}

It seems that node.borrow().right.clone() works.

Yep, RefCell::borrow gives you a smart pointer that is like a shared reference (&_), so you can't move out of it. But you can clone the Rc instead, which is really cheap

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.