Rust 没有异常机制,错误通过 Result<T, E> 类型显式传播,编译器强制调用方处理可能的失败。
一、? 运算符与错误转换
rust
use std::fs::File;
use std::io::{self, Read};
fn read_config() -> io::Result<String> {
let mut file = File::open("config.toml")?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}? 在错误时提前返回,并通过 From trait 自动转换错误类型。
二、库与应用的分层策略
- 库(Library):使用
thiserror定义具体错误枚举,便于调用方精确匹配 - 应用(Application):使用
anyhow简化错误上下文传递
rust
use anyhow::{Context, Result};
fn run() -> Result<()> {
let content = std::fs::read_to_string("config.toml")
.context("failed to read config")?;
Ok(())
}