小编max*_*iri的帖子

为什么这里需要类型注释?

在这个 leetcode 反转二叉树问题中,我试图可变地借用一个包含在 Rc 中的节点。这是代码。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我将这一行更改let n: &mut TreeNode为 just let n = &mut node.borrow_mut(),我会在下一行收到编译器错误,“*n一次不能多次借用可变的”,编译器似乎推断 n 为 类型&mut RefMut<TreeNode>,但是当我明确地显示时,一切都会正常说是吧&mut TreeNode。有什么理由吗?

rust

4
推荐指数
1
解决办法
302
查看次数

标签 统计

rust ×1