for 循环中 Iterator 的元素不是局部作用域的吗?

Isn't the element of Iterator in for loop local scoped?

我有一个简单的结构,如下所示,称为 TopicTree:

#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
// #[allow(dead_code)]
pub struct TopicTree {
    topic_name: String,
    child: Option<Vec<Box<TopicTree>>>,
    data: Option<Vec<String>>
}

还有另一个名为 App 的结构,它有一个 impl 块,如下所示:

struct App {
    // Topic Tree
    topic_tree_root:TopicTree,
}

impl App {
    pub fn parse_topic_to_tree(& mut self, topic: &str){
        let mut temp_node = & mut self.topic_tree_root;
        let mut found = false;
        for text in topic.split("/") {
            for item in temp_node.child.as_mut().unwrap() {
                if item.topic_name == text {
                    temp_node = item.as_mut();
                    found = true;
                    break;
                }
            }
        }
    }
}

当我尝试编译代码时,rustc 给我这个错误:

error[E0499]: cannot borrow `temp_node.child` as mutable more than once at a time
  --> src/pub/lib/app.rs:22:26
   |
22 |                 for j in temp_node.child.as_mut().unwrap() {
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^ `temp_node.child` was mutably borrowed here in the previous iteration of the loop

所以我的问题是,变量 item 不是局部范围的吗?如果不是这样,我如何在嵌套循环中迭代 temp_node.child,这是必要的,因为 temp_node 也是 可变的 .

为了执行内部循环,编译器必须 1) 在 temp_node 上创建隐式借用,以便 2) 借用 temp_node.child,以便调用 as_mut() (这需要 &mut self),然后将结果绑定到 itemitem 的寿命取决于 temp_node 是否活着,因此 borrow-chain.

在外循环的后续迭代中,发生冲突:如果temp_node = item.as_mut()已经执行,则需要在for item = ...行可变借用temp_node。但它已经被借来让 temp_item 活着,它来自 item,来自 temp_node... 在这里,循环逻辑可能变得明显:无法保证 -在编写代码时,尽管数据结构不支持这一点——temp_nodeitem 最终成为 同一个对象 ,这将导致两个可变借用相同的值。

这里的 mut&mut 可能有些混淆。 temp_node 需要是 mut(如 let mut,因为你更改了 temp_node),但它不需要是 &mut(如“可变借”,因为您不是修改引用后面的数据。