如何解决由于过滤 read_dir 输出而“无法移出借用的内容”?

问题描述 投票:0回答:1

我正在尝试使用

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
的各种组合,但无济于事。发生什么事了?

rust borrow-checker
1个回答
2
投票

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(())
}
© www.soinside.com 2019 - 2024. All rights reserved.