由于过滤 read_dir 输出,如何解决 "cannot move out of borrowed content"?

How to resolve "cannot move out of borrowed content" due to filtering read_dir output?

我正在尝试使用 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<_>>>();

(playground)

错误信息是:

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(())
}