繁体   English   中英

Rust - 不能作为可变借用

[英]Rust - cannot borrow as mutable

我想了解如何在二叉树的节点中插入值:

use std::rc::Rc;
use std::cell::RefCell;

// Definition for a binary tree node.
#[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
    }
  }
}

/*
            1
          /  \
         2   3
       / 
      4 
*/

fn main() {
    let mut t = TreeNode::new(1);
    t.left = Some(Rc::new(RefCell::new (TreeNode::new(2))));
    t.right = Some(Rc::new(RefCell::new(TreeNode::new(3))));
    t.left.unwrap().get_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(4)))); // throws error
}

操场

树应该看起来像评论中的那个。 编译时会抛出错误:

error[E0596]: cannot borrow data in an `Rc` as mutable
  --> src/main.rs:35:5
   |
35 |     t.left.unwrap().get_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(4))));
   |     ^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<RefCell<TreeNode>>`

如何将新的 TreeNode 分配到值2的左侧?

更新:我无法将left类型从 Option<Rc< right Option<Rc<RefCell<TreeNode>>>更改为其他任何内容。 谢谢!

也许你的意思是borrow_mut()而不是get_mut()

fn main() {
    let mut t = TreeNode::new(1);
    t.left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
    t.right = Some(Rc::new(RefCell::new(TreeNode::new(3))));
    t.left.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(4))));
}

考虑到更新后的问题,您正在寻找的咒语是

t.left.unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(4))));

get_mut用于当您已经拥有对RefCell的可变引用,并且出于安全原因您永远不会对Rc中的事物进行可变引用时。 另一方面, borrow_mut用于规避通常的规则并获得对不可变事物的可变引用。 请注意,在任何一种情况下, Rc都是透明的,因为Deref特性会为我们处理它。

它既冗长又笨拙,坦率地说,我为此责怪 Leetcode。 我怀疑他们告诉某人 go 将所有内容翻译成 Rust,而那个人不知道 Rust,只是将所有内容都扔到了RefCell中,因为他们不知道更好。 所以请不要把它当作惯用的 Rust 的良好代表。 该示例代码丑陋,简单明了。 Rust 是比这更漂亮的语言,我是 promise。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM