【发布时间】:2016-10-28 16:43:55
【问题描述】:
我试图在循环中重新分配一个变量,但我一直遇到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()
}
}
【问题讨论】:
-
唯一的解决方案是以规避问题的方式重写代码。关于
Node是什么以及您期望得到什么的更多详细信息,因为这个函数的输出将是无价的(在问题中编辑它们)。 -
这不是正确的术语(我充其量只是一个 rust 新手),但在我看来,您的
cur_node_borrowed拥有cur_node的可变借用所有权。因此,当您深究时,您会尝试再次变异cur_node而cur_node_borrowed在范围内。将cur_node_borrowed推到范围之外 - 从而失去可变借用 - 应该让您再次分配给 cur_node 。 (我只是不知道你这样做的最佳方式,抱歉)。希望这能为您指明正确的方向。 -
@MatthieuM,我添加了我的节点实现。目标是根据子节点的最大值返回节点向量。为简洁起见,我将其删除。
标签: rust