欢迎访问 内存溢出 —— 独立后端与系统工程技术博客

专注于分布式系统、Linux内核、数据库存储与后端工程实践

Rust 错误处理:Result、? 运算符与 anyhow/thiserror 实践

发表于:|最后更新:|分类:系统编程|阅读:2276 次

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(())
}