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

时间:2016-10-28 16:43:55

标签: rust

我试图在循环中重新分配变量,但我一直在运行main()。下面我简单地说明了循环,它也是同样的问题。我该如何处理?

cannot assign to `cur_node` because it is borrowed

1 个答案:

答案 0 :(得分:3)

正如评论所说,您需要重新构建代码,以确保在您要分配给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()
            }
        };
    }
}
相关问题