Rust 错误处理:天塌下来当被盖
Rust 将错误分为两大类:可恢复错误 (如文件未找到) 和 不可恢复错误 (如数组越界)。
💥 不可恢复错误:panic!
当遇到无法挽回的问题时,程序会直接崩溃退出。
fn main() {
panic!("皇上驾崩啦!");
}
🛡️ 可恢复错误:Result<T, E>
大多数错误都是可以处理的。Rust 使用 Result 枚举来返回成功或失败。
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!("文件打不开: {:?}", error);
},
};
}
🔪 简写:unwrap 和 expect
如果你确信不会出错,或者懒得处理错误(直接崩溃),可以用这两个方法。
let f = File::open("hello.txt").unwrap(); // 出错就 panic
let f = File::open("hello.txt").expect("文件必须存在!"); // 出错 panic 并打印信息
🛠️ Result 常用招式
除了 match 和 unwrap,还有很多优雅的处理方式:
is_ok()/is_err(): 检查成功还是失败(返回 bool)。unwrap_or(default): 失败时返回默认值(备选方案)。unwrap_or_else(closure): 失败时执行闭包计算默认值(更懒)。
❓ 传播错误:? 运算符
如果函数里处理不了错误,可以把错误抛给调用者。
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
// 如果 open 失败,直接返回 Err
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}