我试图在循环中重新分配一个变量,但我一直遇到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/