Loops 递归访问Hashmap中的枚举
我用一个枚举、两个结构和一个BTreeMap为一个类似文件系统的结构建模,如下所示(简化): 但我得到:Loops 递归访问Hashmap中的枚举,loops,enums,hashmap,iteration,rust,Loops,Enums,Hashmap,Iteration,Rust,我用一个枚举、两个结构和一个BTreeMap为一个类似文件系统的结构建模,如下所示(简化): 但我得到: error: cannot move out of borrowed content [E0507] for (_, child) in index.children { ^~~~~ 我也试过了 for (_, child) in index.children.iter() { 但是我得到了 error: mismatche
error: cannot move out of borrowed content [E0507]
for (_, child) in index.children {
^~~~~
我也试过了
for (_, child) in index.children.iter() {
但是我得到了
error: mismatched types:
expected `&Item`,
found `Item`
(expected &-ptr,
found enum `Item`) [E0308]
src/... Item::File(mut a) => {
^~~~~~~~~~~~~~~~~
我尝试了几种组合:
for (_, child) in &(index.children)
for (_, child) in index.children.iter().as_ref()
match(child) { Item::File(&mut f) =>
match(child) { Item::File(ref mut f) =>
等等,但找不到让借钱人高兴的方法
非常感谢您的帮助。您的代码有几个问题。以下是带有编号更改的工作版本:
fn process(index: &mut Dir) {
// ^^^-- #2
for (_, child) in &mut index.children {
// ^^^-- #1
match *child {
//^-- #3
Item::File(ref mut f) => {
// ^^^-- #4
f.do_something();
},
Item::Dir(ref mut d) => {
// ^^^-- #4
process(d);
}
}
}
}
在index.children
中,尝试将子项
移动到迭代中。已经有很多人在解释为什么会这样。我们希望在不消耗的情况下进行迭代,但能够改变值Dir
child
是类型为和mut Item
的可变引用(因为迭代器会产生这种引用)。匹配块(Item::File(/*…*/)
中的模式具有类型Item
。这是类型不匹配(第二个编译器错误)。我们可以通过使用*
取消对子项的引用来解决这个问题
match
块与Item
匹配,但我们实际上并不拥有该项,也无法移出它。为了防止移动,我们添加ref
关键字。现在f
和d
是参考,我们避免了移动您的代码有几个问题。以下是带有编号更改的工作版本:
fn process(index: &mut Dir) {
// ^^^-- #2
for (_, child) in &mut index.children {
// ^^^-- #1
match *child {
//^-- #3
Item::File(ref mut f) => {
// ^^^-- #4
f.do_something();
},
Item::Dir(ref mut d) => {
// ^^^-- #4
process(d);
}
}
}
}
在index.children
中,尝试将子项
移动到迭代中。已经有很多人在解释为什么会这样。我们希望在不消耗的情况下进行迭代,但能够改变值Dir
child
是类型为和mut Item
的可变引用(因为迭代器会产生这种引用)。匹配块(Item::File(/*…*/)
中的模式具有类型Item
。这是类型不匹配(第二个编译器错误)。我们可以通过使用*
取消对子项的引用来解决这个问题
match
块与Item
匹配,但我们实际上并不拥有该项,也无法移出它。为了防止移动,我们添加ref
关键字。现在f
和d
是参考,我们避免了移动非常感谢。你的解释在1。是我尝试使用.iter()的原因(因为它返回引用)。我发现手册在总体上非常混乱&、&mut、ref和*以及您可以使用它们的地方。在函数参数和调用参数中使用时,它们的作用是非常清楚的,但我从未尝试在for…in或a*匹配后使用&mut…谢谢!你的解释在1。是我尝试使用.iter()的原因(因为它返回引用)。我发现手册在总体上非常混乱&、&mut、ref和*以及您可以使用它们的地方。当在函数参数和调用参数中使用时,它们的作用是非常清楚的,但我从来没有尝试在for…in或a*after match之后使用&mut。。。
fn process(index: &mut Dir) {
// ^^^-- #2
for (_, child) in &mut index.children {
// ^^^-- #1
match *child {
//^-- #3
Item::File(ref mut f) => {
// ^^^-- #4
f.do_something();
},
Item::Dir(ref mut d) => {
// ^^^-- #4
process(d);
}
}
}
}