【发布时间】:2021-07-13 20:50:27
【问题描述】:
我的第一个rust 程序/函数应该遍历目录树并提供HashMap 与K(mime_as_string) 和V(count_sum, size_sum)。我想要它的 FP 风格。
所以我拥有的是这样的:
fn files_info4(rootpath: &str) {
struct FTypeStats {
count: u64,
size: u64,
}
impl Default for FTypeStats {
fn default() -> Self {
FTypeStats {
count: 0,
size: 0,
}
}
}
// get file type stats directly/functionally/lazy
let fts = WalkDir::new(rootpath)
.min_depth(1)
.max_depth(99)
.into_iter()
.filter_map(|entry| entry.ok())
.map(|entry| (entry, entry.metadata().map_or(false, |m| m.is_file())))
.filter(|(e, f)| *f)
.fold(HashMap::new(), | mut acc: HashMap<String, FTypeStats>, (e, _) | {
let ftype = tree_magic::from_filepath(e.path());
acc.get_mut(&ftype).unwrap_or_default().count += 1;
acc.get_mut(&ftype).unwrap_or_default().size += e.metadata().map_or(0, |m| m.len());
acc
});
}
遇到错误后我在哪里做impl Default:
error[E0599]: the method `unwrap_or_default` exists for enum `Option<&mut FTypeStats>`, but its trait bounds were not satisfied
--> src/main.rs:54:29
|
54 | acc.get_mut(&ftype).unwrap_or_default().count += 1;
| ^^^^^^^^^^^^^^^^^ method cannot be called on `Option<&mut FTypeStats>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`&mut FTypeStats: Default`
但它仍然没有帮助,即仍然存在相同的错误。
问题:
- 如何编译/运行
- 可以优化评估链吗? (
fold中的代码实际上是否正确,例如我需要为FTypeStats进行的分配和初始化默认/初始值?(感觉有点“隐含”))
TIA!
【问题讨论】:
标签: rust functional-programming