深度优先树搜索期间的多个可变借用

Multiple mutable borrows during a depth-first tree search

如何重构这个进行深度优先搜索和 returns 匹配节点的父节点的函数?

我知道这个问题的变体经常出现(例如 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

通过搜索、记录其中的一些数据,然后在循环外有效地计算 return 值,可以一次完成此操作:

let mut found = Err(());
for (i, child) in root.children.iter_mut().enumerate() {
    if child.id == id {
        found = Ok(None);
        break;
    }  else find_parent_mut(child, id).is_some() {
        found = Ok(Some(i));
        break;
    }
}
match found {
    Ok(Some(i)) => Some(&mut root.children[i]),
    Ok(None) => Some(root),
    Err(()) => None,
}

这通过完全避免内部循环中的 returns 避免了由条件 returning 可变变量(这是您和我在下面的回答遇到的问题)引起的问题。


Old/incorrect回答:

我现在无法测试我的建议,但我认为解决此问题的最佳方法是 return root 循环外。

for child in &mut root.children {
    if child.id == id {
        found = true;
        break
    } ...
}
if found {
    Some(root)
} else {
    None
}

这(希望)确保 root 在被操纵时不会通过 children 借用。

但是我怀疑主循环中的早期 return 可能会干扰,在这种情况下,可能只需要退回到整数和索引:

for i in 0..root.children.len() {
    if root.children[i].id == id {
        return Some(root)
    ...
}

我设法让它以这种方式工作:

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(..) 函数以一种更像迭代器的方式折叠它。

对于第二个循环,我不太确定发生了什么,显然将引用绑定到变量使借用检查器感到困惑。我删除了任何临时变量,现在它可以编译了。