for 循环中的迭代器元素不是本地范围的吗?



我有一个简单的结构体,就像下面的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的结构体它有一个implBlock如下:

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是否活着,因为这个借用链。

在外部循环的后续迭代中,会发生冲突:如果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(如"可变借用",因为您没有修改引用背后的数据)。

最新更新