enum Result<T, E> {Ok(T),Err(E),}
use std::fs::File;fn main() {let f = File::open("hello.txt");let f = match f {Ok(file) => file,Err(error) => panic!("Problem opening the file: {:?}", error),};}
匹配不同的错误
use std::fs::File;use std::io::ErrorKind;fn main() {let f = File::open("hello.txt");let f = match f {Ok(file) => file,Err(error) => match error.kind() {ErrorKind::NotFound => match File::create("hello.txt") {Ok(fc) => fc,Err(e) => panic!("Problem creating the file: {:?}", e),},other_error => {panic!("Problem opening the file: {:?}", other_error)}},};}
失败时 panic 的简写:unwrap 和 expect
unwrap:如果 Result 值是成员 Ok,unwrap 会返回 Ok 中的值。如果 Result 是成员 Err,unwrap 会为我们调用 panic!。
use std::fs::File;fn main() {let f = File::open("hello.txt").unwrap();}thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error {repr: Os { code: 2, message: "No such file or directory" } }',src/libcore/result.rs:906:4
expect:指定错误信息
use std::fs::File;fn main() {let f = File::open("hello.txt").expect("Failed to open hello.txt");}
传播错误
传播错误:可以选择让调用者知道这个错误并决定该如何处理
#![allow(unused)]fn main() {use std::fs::File;use std::io::{self, Read};fn read_username_from_file() -> 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),}}}
传播错误的简写:?运算符
#![allow(unused)]fn main() {use std::fs::File;use std::io::{self, Read};fn read_username_from_file() -> Result<String, io::Error> {let mut f = File::open("hello.txt")?;let mut s = String::new();f.read_to_string(&mut s)?;Ok(s)}}
? 运算符所使用的错误值被传递给了 from 函数,它定义于标准库的 From trait 中,其用来将错误从一种类型转换为另一种类型。当 ? 运算符调用 from 函数时,收到的错误类型被转换为由当前函数返回类型所指定的错误类型。
#![allow(unused)]fn main() {use std::fs::File;use std::io::{self, Read};fn read_username_from_file() -> Result<String, io::Error> {let mut s = String::new();File::open("hello.txt")?.read_to_string(&mut s)?;Ok(s)}}
最简单的写法
#![allow(unused)]fn main() {use std::fs;use std::io;fn read_username_from_file() -> Result<String, io::Error> {fs::read_to_string("hello.txt")}}
Rust 提供了名为 fs::read_to_string 的函数,它会打开文件、新建一个 String、读取文件的内容,并将内容放入 String,接着返回它。
