|
|
|
@ -135,19 +135,19 @@ use std::fs::File;
|
|
|
|
|
use std::io::ErrorKind;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let f = File::open("hello.txt").map_err(|error| {
|
|
|
|
|
let f = File::open("hello.txt").unwrap_or_else(|error| {
|
|
|
|
|
if error.kind() == ErrorKind::NotFound {
|
|
|
|
|
File::create("hello.txt").unwrap_or_else(|error| {
|
|
|
|
|
panic!("Tried to create file but there was a problem: {:?}", error);
|
|
|
|
|
panic!("Problem creating the file: {:?}", error);
|
|
|
|
|
})
|
|
|
|
|
} else {
|
|
|
|
|
panic!("There was a problem opening the file: {:?}", error);
|
|
|
|
|
panic!("Problem opening the file: {:?}", error);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
在阅读完第十三章后再回到这个例子,并查看标准库文档 `map_err` 和 `unwrap_or_else` 方法都做了什么操作。还有很多这类方法可以消除大量处理错误时嵌套的 `match` 表达式。
|
|
|
|
|
在阅读完第十三章后再回到这个例子,并查看标准库文档 `unwrap_or_else` 方法都做了什么操作。在处理错误时,还有很多这类技巧可以消除大量嵌套的 `match` 表达式。
|
|
|
|
|
|
|
|
|
|
### 失败时 panic 的简写:`unwrap` 和 `expect`
|
|
|
|
|
|
|
|
|
|