我试图在循环中重新分配变量,但我不断遇到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 的编译方法块是表达式 https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html特征:
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()
}
};
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)