无法分配给变量,因为它是借用的

New*_*ang 12 rust

我试图在循环中重新分配变量,但我不断遇到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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*son 9

正如评论所说,您将需要重组代码以确保在您想要分配给 的位置没有借用cur_node。在与人打交道时,Rc您通常也可以逃脱一些额外的惩罚.clone(),但这是作弊(而且效率稍低):-)。

这是一种利用 Rust 的块是表达式功能的编译方法:

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