我有一个简单的结构体,就像下面的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
),然后将结果绑定到item
。item
的生命周期取决于temp_node
是否活着,因为这个借用链。
在外部循环的后续迭代中,会发生冲突:如果temp_node = item.as_mut()
已经执行,则需要在for item = ...
行中可变地借用temp_node
。但它已经被借用来维持temp_item
的生存,item
来自temp_node
……在这里,循环逻辑可能变得很明显:不能保证——在编写代码时,尽管数据结构不支持这一点——temp_node
和item
最终是相同的对象,这将导致对同一值的两个可变借用。
这里可能会有一些关于mut
和&mut
的混淆。temp_node
需要是mut
(如let mut
,因为您更改了temp_node
),但它不需要是&mut
(如"可变借用",因为您没有修改引用背后的数据)。