错误处理
土豆 2023/3/11
可恢复错误与 Result
use std::fs::File;
fn main() {
// f 类型 Result<File,Error>
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => {
panic!("There was a problem opening the file: {:?}", error);
}
};
}
匹配不同的错误
// #[derive(Debug)]
use std::fs::File;
use std::io::ErrorKind;
fn main() {
// f 类型 Result<File,Error>
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!("Tried to create file but there was a problem:{:?}", e),
},
other_error => panic!("There was a problem opening the file: {:?}", other_error),
},
};
}
失败时触发 panic 的快捷⽅式:unwrap 和 expect
use std::fs::File;
fn main() {
// unwrap 方式,如果错则打印错误,否则返回正确的file
let f = File::open("hello.txt").unwrap();
// 传入panic错误信息
let f = File::open("hello.txt").expect("Failed to open hello.txt");
}
传播错误
use std::fs::File;
use std::io;
use std::io::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),
}
}