1. enum Result<T, E> {
  2. Ok(T),
  3. Err(E),
  4. }
  1. use std::fs::File;
  2. fn main() {
  3. let f = File::open("hello.txt");
  4. let f = match f {
  5. Ok(file) => file,
  6. Err(error) => panic!("Problem opening the file: {:?}", error),
  7. };
  8. }

匹配不同的错误

  1. use std::fs::File;
  2. use std::io::ErrorKind;
  3. fn main() {
  4. let f = File::open("hello.txt");
  5. let f = match f {
  6. Ok(file) => file,
  7. Err(error) => match error.kind() {
  8. ErrorKind::NotFound => match File::create("hello.txt") {
  9. Ok(fc) => fc,
  10. Err(e) => panic!("Problem creating the file: {:?}", e),
  11. },
  12. other_error => {
  13. panic!("Problem opening the file: {:?}", other_error)
  14. }
  15. },
  16. };
  17. }

失败时 panic 的简写:unwrap 和 expect

unwrap:如果 Result 值是成员 Ok,unwrap 会返回 Ok 中的值。如果 Result 是成员 Err,unwrap 会为我们调用 panic!。

  1. use std::fs::File;
  2. fn main() {
  3. let f = File::open("hello.txt").unwrap();
  4. }
  5. thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error {
  6. repr: Os { code: 2, message: "No such file or directory" } }',
  7. src/libcore/result.rs:906:4

expect:指定错误信息

  1. use std::fs::File;
  2. fn main() {
  3. let f = File::open("hello.txt").expect("Failed to open hello.txt");
  4. }

传播错误

传播错误:可以选择让调用者知道这个错误并决定该如何处理

  1. #![allow(unused)]
  2. fn main() {
  3. use std::fs::File;
  4. use std::io::{self, Read};
  5. fn read_username_from_file() -> Result<String, io::Error> {
  6. let f = File::open("hello.txt");
  7. let mut f = match f {
  8. Ok(file) => file,
  9. Err(e) => return Err(e),
  10. };
  11. let mut s = String::new();
  12. match f.read_to_string(&mut s) {
  13. Ok(_) => Ok(s),
  14. Err(e) => Err(e),
  15. }
  16. }
  17. }

传播错误的简写:?运算符

  1. #![allow(unused)]
  2. fn main() {
  3. use std::fs::File;
  4. use std::io::{self, Read};
  5. fn read_username_from_file() -> Result<String, io::Error> {
  6. let mut f = File::open("hello.txt")?;
  7. let mut s = String::new();
  8. f.read_to_string(&mut s)?;
  9. Ok(s)
  10. }
  11. }

? 运算符所使用的错误值被传递给了 from 函数,它定义于标准库的 From trait 中,其用来将错误从一种类型转换为另一种类型。当 ? 运算符调用 from 函数时,收到的错误类型被转换为由当前函数返回类型所指定的错误类型。

  1. #![allow(unused)]
  2. fn main() {
  3. use std::fs::File;
  4. use std::io::{self, Read};
  5. fn read_username_from_file() -> Result<String, io::Error> {
  6. let mut s = String::new();
  7. File::open("hello.txt")?.read_to_string(&mut s)?;
  8. Ok(s)
  9. }
  10. }

最简单的写法

  1. #![allow(unused)]
  2. fn main() {
  3. use std::fs;
  4. use std::io;
  5. fn read_username_from_file() -> Result<String, io::Error> {
  6. fs::read_to_string("hello.txt")
  7. }
  8. }

Rust 提供了名为 fs::read_to_string 的函数,它会打开文件、新建一个 String、读取文件的内容,并将内容放入 String,接着返回它。