【问题标题】:Cannot assign to variable because it is borrowed无法分配给变量,因为它是借来的
【发布时间】:2016-10-28 16:43:55
【问题描述】:

我试图在循环中重新分配一个变量,但我一直遇到cannot assign to `cur_node` because it is borrowed。下面我为了简单起见注释掉了循环,这是同样的问题。我该如何处理?

fn naive_largest_path(root: Rc<RefCell<Node>>) {
    let mut cur_node = root.clone();
    let cur_node_borrowed = cur_node.borrow();

    // while cur_node_borrowed.has_children() {
        let lc = cur_node_borrowed.left_child.as_ref().unwrap();

        let left_child = cur_node_borrowed.left_child.as_ref().unwrap();
        let right_child = cur_node_borrowed.right_child.as_ref().unwrap();

        let left_val = left_child.borrow().value;
        let right_val = right_child.borrow().value;

        if left_val > right_val {
            cur_node = left_child.clone();
        } else {
            cur_node = right_child.clone();
        }
    // }
}

struct Node {
    value: i32,
    row_num: i32,
    position_in_row: i32,
    left_child: Option<Rc<RefCell<Node>>>,
    right_child: Option<Rc<RefCell<Node>>>,
}

impl Node {
    fn new(val: i32, row: i32, pos_in_row: i32) -> Rc<RefCell<Node>> {
        Rc::new(RefCell::new(Node {
            value: val,
            row_num: row,
            position_in_row: pos_in_row,
            left_child: None,
            right_child: None,
        }))
    }

    fn has_children(&self) -> bool {
        self.left_child.is_some() || self.right_child.is_some()
    }
}

【问题讨论】:

  • 唯一的解决方案是以规避问题的方式重写代码。关于Node 是什么以及您期望得到什么的更多详细信息,因为这个函数的输出将是无价的(在问题中编辑它们)。
  • 这不是正确的术语(我充其量只是一个 rust 新手),但在我看来,您的 cur_node_borrowed 拥有 cur_node 的可变借用所有权。因此,当您深究时,您会尝试再次变异 cur_nodecur_node_borrowed 在范围内。将cur_node_borrowed 推到范围之外 - 从而失去可变借用 - 应该让您再次分配给 cur_node 。 (我只是不知道你这样做的最佳方式,抱歉)。希望这能为您指明正确的方向。
  • @MatthieuM,我添加了我的节点实现。目标是根据子节点的最大值返回节点向量。为简洁起见,我将其删除。

标签: rust


【解决方案1】:

正如 cmets 所说,您需要重新构建代码以确保在要分配给 cur_node 的位置没有借位。与Rc 打交道时,您通常还可以通过一些额外的.clone() 侥幸逃脱,但这是作弊(而且效率稍低):-)。

这是一种利用 Rust 的 blocks-are-expressions 功能进行编译的方式:

fn naive_largest_path(root: Rc<RefCell<Node>>) {

    let mut cur_node = root.clone();

    while cur_node.borrow().has_children() {
        cur_node = {
            let cur_node_borrowed = cur_node.borrow();

            let lc = cur_node_borrowed.left_child.as_ref().unwrap();

            let left_child = cur_node_borrowed.left_child.as_ref().unwrap();
            let right_child = cur_node_borrowed.right_child.as_ref().unwrap();



            let left_val = left_child.borrow().value;
            let right_val = right_child.borrow().value;


            if left_val > right_val {
                left_child.clone()
            } else {
                right_child.clone()
            }
        };
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多