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

标签 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()
    }
}

最佳答案

如评论所述,您需要重构代码以确保在您要分配给 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()
            }
        };
    }
}

关于rust - 无法分配给变量,因为它是借用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309585/

相关文章:

rust - 丢弃最后一个发件人但收信人仍处于事件状态时,是否可以在Tokio MPSC中保留项目?

parsing - 如何在 Rust 中为我自己的解析器编写组合器?

rust - Rust 可以调用抽象函数吗?

rust - 通用数字的函数签名

rust - Cap'n proto 的可变状态

rust - 从函数返回堆分配的值?

reference - Rust的确切自动引用规则是什么?

rust - tonic_build 添加/使用外部 crate ,如 serde

struct - 为什么默认(结构值)数组初始化需要 Copy 特征?

rust - 用特征别名替换特征绑定(bind)说 "the size for values cannot be known at compilation time"