我正在尝试使用
read_dir
读取目录的内容,然后仅过滤文件:
let xs = std::fs::read_dir(".")?
.filter(|r_entry| {
r_entry.and_then(|entry| {
let m = entry.metadata()?;
Ok(m.is_file())
})
.unwrap_or(false)
})
.collect::<Result<Vec<_>>>();
(游乐场)
错误信息是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:6:13
|
6 | r_entry
| ^^^^^^^ cannot move out of borrowed content
我尝试了
&
和*
围绕r_entry
的各种组合,但无济于事。发生什么事了?
filter
中的谓词只允许你借用r_entry
。当您调用 and_then
时,这将尝试移动。相反,您可以在 match
中使用引用,如下所示:
fn main() -> Result<()> {
let xs = std::fs::read_dir(".")?
.filter(|r_entry| match r_entry {
Ok(entry) => entry.metadata().map(|m| m.is_file()).unwrap_or(false),
Err(_) => false,
})
.collect::<Result<Vec<_>>>();
println!("{:?}", xs);
Ok(())
}