2016-11-15 56 views
2

我想处理io::Result<DirEntry>返回从items迭代返回std::fs::read_dir()函数。我关心的是如何从Result申请时matchOk处理io ::结果<DirEntry>没有返回错误

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` 
} 

我想还有以下

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 
    } 

也许有处理Result没有的情况下使用match一种更好的方式获得的DirEntry值喜欢这个?

+0

看起来你并不需要把它弄出来的是范围,你可以做'好了的(de)=> {/ *做的东西去* /}' – wimh

+0

我知道我能做到这但我想尽可能避免嵌套。 – MusuNaji

回答

6

您在match之外声明变量的尝试是正确的。您会收到有关可能未初始化的变量的错误消息,因为您不会强制执行流程继续执行分支上的下一次迭代。您可以将continue添加到Err分支中。然后通过将match表达式的结果直接分配给变量,可以按照与变量files相同的方式对变量进行初始化。

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

谢谢你的帮助,我现在看到'继续'的必要性了。 – MusuNaji