处理io :: Result <DirEntry>而不返回Err

Ido*_*nts 2 rust

我想把手io::Result<DirEntry>从迭代上返回itemsstd::fs::read_dir()功能.我关心的是如何DirEntrymatchResult何时开始申请时获得价值Ok

let files = match fs::read_dir(&dir_path) {
    Ok(items) => items,
    //I actually want to leave function if there is an error here
    Err(_) => return Err("Cannot read directory items".to_string()),
};
for item in files { // item: io::Result<DirEntry>
    match item {
      Ok(de) => de,// how to get `de` out of this scope??
      //here I just want to print error and loop for next item
      Err(_) => println!("{:?} cannot be accessed", item),
    };
    //do something with `de`
}
Run Code Online (Sandbox Code Playgroud)

我也试过以下

  let files = match fs::read_dir(&dir_path) {
    Ok(items) => items,
    Err(_) => return Err("Cannot read directory items".to_string()),
  };

  for item in files {
    let file: DirEntry; // I get compile error for use of possibly uninitialized `file`
    match item {
      Ok(de) => file = de,
      Err(_) => println!("{:?} cannot be accessed", item),
    };
    //do somthing with file
  }
Run Code Online (Sandbox Code Playgroud)

也许在Result没有使用match这种情况下有更好的处理方式?

Fra*_*gné 6

您在外部声明变量的尝试match是在正确的轨道上.您收到一个可能未初始化的变量的错误,因为您没有强制执行流程进展到Err分支上的下一个迭代.您可以通过添加continueErr分支来完成此操作.然后files,通过将match表达式的结果直接赋值给变量,可以以与变量相同的方式初始化变量.

for item in files {
    let file = match item {
        Ok(de) => de,
        Err(_) => {
            println!("{:?} cannot be accessed", item);
            continue;
        }
    };
    // do something with file
    file;
}
Run Code Online (Sandbox Code Playgroud)