【发布时间】:2016-07-15 17:50:30
【问题描述】:
我用一个枚举、两个结构和一个 BTreeMap 建模了一个类似文件系统的结构,如下所示(简化):
pub enum Item {
Dir(Dir),
File(File),
}
struct Dir {
...
children: BTreeMap<String, Item>,
}
struct File {
...
}
现在我需要遍历一个目录并对每个文件进行一些操作。我试过这个:
fn process(index: &Dir) {
for (_, child) in index.children {
match child {
Item::File(mut f) => {
let xyz = ...;
f.do_something(xyz);
},
Item::Dir(d) => {
process(&d);
}
}
}
}
但我明白了:
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) =>
等等,但找不到让借阅检查员满意的方法。
非常感谢任何帮助。
【问题讨论】:
标签: loops enums hashmap iteration rust