1 panic!```rust
let f = File::open(“hello.txt”); match f { Ok(file) => file, Err(error) => panic!(“There was a problem opening the file: {:?}”, error), };
<a name="kS4Ro"></a>
# 2 Result常常用作函数的返回值```rust
enum Result<T, E> {
Ok(T),
Err(E),
}
// 返回值类型为std::result::Result<std::fs::File, std::io::Error>
let f = File::open("hello.txt");
match f {
Ok(file) => file,
Err(error) => panic!("There was a problem opening the file: {:?}", error),
};
2.1 std::io::Error的kind()函数返回错误类型```rust
match f { Ok(file) => file, // match guard Err(ref error) if error.kind() == ErrorKind::NotFound => { match File::create(“hello.txt”) { Ok(fc) => fc, Err(e) => panic!(“there was a problem: {:?}”, e), } } Err(error) => panic!(“opening the file failed: {:?}”, error), };
<a name="j4gDa"></a>
## 2.2 简易写法: unwrap 在返回错误时直接panic```rust
fn demo3() {
File::open("hello.txt").unwrap();
}
2.3 简易写法: expect 在返回错误时直接panic,但允许指定错误描述信息```rust
fn demo4() { File::open(“hello.txt”).expect(“打开文件失败”); }
<a name="HYuF1"></a>
# 3 处理错误```rust
fn demo5() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
3.1 语法糖:?```rust
fn demo6() -> Result
<a name="9Gdou"></a>
## 3.2 ?的串接
fn demo7() -> Result
- 注意:?只能用于返回值为Result的函数中