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), };

  1. <a name="kS4Ro"></a>
  2. # 2 Result常常用作函数的返回值```rust
  3. enum Result<T, E> {
  4. Ok(T),
  5. Err(E),
  6. }
  7. // 返回值类型为std::result::Result<std::fs::File, std::io::Error>
  8. let f = File::open("hello.txt");
  9. match f {
  10. Ok(file) => file,
  11. Err(error) => panic!("There was a problem opening the file: {:?}", error),
  12. };

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), };

  1. <a name="j4gDa"></a>
  2. ## 2.2 简易写法: unwrap 在返回错误时直接panic```rust
  3. fn demo3() {
  4. File::open("hello.txt").unwrap();
  5. }

2.3 简易写法: expect 在返回错误时直接panic,但允许指定错误描述信息```rust

fn demo4() { File::open(“hello.txt”).expect(“打开文件失败”); }

  1. <a name="HYuF1"></a>
  2. # 3 处理错误```rust
  3. fn demo5() -> Result<String, io::Error> {
  4. let f = File::open("hello.txt");
  5. let mut f = match f {
  6. Ok(file) => file,
  7. Err(e) => return Err(e),
  8. };
  9. let mut s = String::new();
  10. match f.read_to_string(&mut s) {
  11. Ok(_) => Ok(s),
  12. Err(e) => Err(e),
  13. }
  14. }

3.1 语法糖:?```rust

fn demo6() -> Result { let mut s = String::new(); let mut f = File::open(“hello.txt”)?; f.read_to_string(&mut s)?; Ok(s) }

  1. <a name="9Gdou"></a>
  2. ## 3.2 ?的串接

fn demo7() -> Result { let mut s = String::new(); File::open(“hello.txt”)?.read_to_string(&mut s)?; Ok(s) } ```

  • 注意:?只能用于返回值为Result的函数中