如何重构这个执行深度优先搜索并返回匹配节点的父节点的函数?
我知道这个问题的变体经常出现(例如 Multiple mutable borrows when generating a tree structure with a recursive function in Rust 、 Mut borrow not ending where expected ),但我仍然不知道如何修改它才能工作。我尝试过使用切片、std::mem::drop
和添加生命周期参数 where 'a: 'b
的变体,但我仍然没有想出在不可变地借用一个分支中的变量然后在另一个分支中使用该变量的情况下编写它。
#[derive(Clone, Debug)]
struct TreeNode {
id: i32,
children: Vec<TreeNode>,
}
// Returns a mutable reference to the parent of the node that matches the given id.
fn find_parent_mut<'a>(root: &'a mut TreeNode, id: i32) -> Option<&'a mut TreeNode> {
for child in root.children.iter_mut() {
if child.id == id {
return Some(root);
} else {
let descendent_result = find_parent_mut(child, id);
if descendent_result.is_some() {
return descendent_result;
}
}
}
None
}
fn main() {
let mut tree = TreeNode {
id: 1,
children: vec![TreeNode {
id: 2,
children: vec![TreeNode {
id: 3,
children: vec![],
}],
}],
};
let a: Option<&mut TreeNode> = find_parent_mut(&mut tree, 3);
assert_eq!(a.unwrap().id, 2);
}
error[E0499]: cannot borrow `*root` as mutable more than once at a time
--> src/main.rs:11:25
|
9 | for child in root.children.iter_mut() {
| ------------- first mutable borrow occurs here
10 | if child.id == id {
11 | return Some(root);
| ^^^^ second mutable borrow occurs here
...
20 | }
| - first borrow ends here
这是@huon 的建议和持续的编译器错误:
fn find_parent_mut<'a>(root: &'a mut TreeNode, id: i32) -> Option<&'a mut TreeNode> {
for child in root.children {
if child.id == id {
return Some(root);
}
}
for i in 0..root.children.len() {
let child: &'a mut TreeNode = &mut root.children[i];
let descendent_result = find_parent_mut(child, id);
if descendent_result.is_some() {
return descendent_result;
}
}
None
}
error[E0507]: cannot move out of borrowed content
--> src/main.rs:9:18
|
9 | for child in root.children {
| ^^^^ cannot move out of borrowed content
error[E0499]: cannot borrow `root.children` as mutable more than once at a time
--> src/main.rs:15:44
|
15 | let child: &'a mut TreeNode = &mut root.children[i];
| ^^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first mutable borrow occurs here
...
22 | }
| - first borrow ends here
最佳答案
我设法让它以这种方式工作:
fn find_parent_mut<'a>(root: &'a mut TreeNode, id: i32)
-> Option<&'a mut TreeNode> {
if root.children.iter().any(|child| {child.id == id}) {
return Some(root);
}
for child in &mut root.children {
match find_parent_mut(child, id) {
Some(result) => return Some(result),
None => {}
}
}
None
}
首先在第二次尝试中,您编写了
for child in root.children
而不是 for child in &mut root.children
(注意缺少 &mut
),这导致 root.children 被循环消耗而不是仅仅迭代,因此出现 cannot move out of borrowed content
错误。我还使用
any(..)
函数以更迭代器的方式折叠它。对于第二个循环,我不确定发生了什么,显然将引用绑定(bind)到变量混淆了借用检查器。我删除了任何临时变量,现在它可以编译。
关于rust - 深度优先树搜索期间的多个可变借用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29711348/