panic! 处理不可恢复错误。Result<T, E> 处理可恢复错误。? 运算符传播错误。Rust 把错误分为两类:
对应机制:
panic!:不可恢复错误。Result<T, E>:可恢复错误。fn main() { panic!("crash and burn"); }
程序会立即终止,并打印回溯信息(backtrace)。
运行程序时设置环境变量:
RUST_BACKTRACE=1 cargo run
可以看到 panic 发生的位置调用栈。
`panic!` 适合程序进入无法继续的状态,例如内部逻辑不一致。
## 21.4 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!("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) } }, }; }
如果确定操作不会失败,可以用 unwrap:
let f = File::open("hello.txt").unwrap();
或者提供自定义错误信息:
let f = File::open("hello.txt").expect("hello.txt should be included in this project");
生产代码中应谨慎使用 `unwrap`,建议用 `?` 或 `match` 处理错误。
## 21.7 ? 运算符
? 用于简化 Result 的错误传播:
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) }
如果 File::open 返回 Err,函数会立即返回这个 Err;否则继续执行。
? 也可以用于 Option:
fn last_char_of_first_line(text: &str) -> Option<char> { text.lines().next()?.chars().last() }
从 Rust 1.26 起,main 也可以返回 Result:
use std::fs::File; fn main() -> Result<(), Box<dyn std::error::Error>> { let f = File::open("hello.txt")?; Ok(()) }
| 情况 | 机制 | 示例 |
| 不可恢复错误 | panic! | 内部 bug |
| 可恢复错误 | Result<T, E> | 文件不存在 |
| 确定不会失败 | unwrap / expect | 快速原型 |
| 传播错误 | ? | 函数返回 Result |
panic!,什么时候应该使用 Result?unwrap 和 expect 有什么区别?? 运算符改写一段使用 match 处理 Result 的代码。