在这个leetcode倒置二叉树问题中,我试图borrow 一个可变地包装在RC中的 node .以下是代码.
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
let mut stack: Vec<Option<Rc<RefCell<TreeNode>>>> = vec![root.clone()];
while stack.len() > 0 {
if let Some(node) = stack.pop().unwrap() {
let n: &mut TreeNode = &mut node.borrow_mut();
std::mem::swap(&mut n.left, &mut n.right);
stack.extend(vec![n.left.clone(), n.right.clone()]);
}
}
root
}
}
如果我将第let n: &mut TreeNode
行更改为只有let n = &mut node.borrow_mut()
行,则在下一行收到一个编译器错误,"Cannot Born *n
as Mariable At More One Time"
似乎编译器推断n是&mut RefMut<TreeNode>
类型,但当我显式地说它是&mut TreeNode
时,一切都解决了.有什么原因吗?