Z
ZHANK
编程在线教程Rust 教程错误处理 Result 与 ?
模式匹配与错误

错误处理 Result 与 ?

? 运算符传播错误、map_err/and_then 链式、自定义错误类型

错误处理 Result 与 ?

Rust 没有异常——Result<T, E> + ? 运算符让错误处理显式、安全、不遗漏。

学完本章你将: 掌握 ? 运算符传播、map_err/and_then 链式、自定义错误。


? 传播错误

rust
use std::fs;
use std::io;

fn read_username() -> Result<String, io::Error> {
    let s = fs::read_to_string("username.txt")?;  // 出错立即返回
    Ok(s.trim().to_string())
}

// 等价于:
fn read_username_verbose() -> Result<String, io::Error> {
    match fs::read_to_string("username.txt") {
        Ok(s) => Ok(s.trim().to_string()),
        Err(e) => return Err(e),
    }
}

链式处理

rust
fn process_file() -> Result<(), Box<dyn std::error::Error>> {
    let content = fs::read_to_string("data.txt")
        .map_err(|e| format!("读取文件失败: {}", e))?;

    let num: i32 = content.trim().parse()
        .map_err(|e| format!("解析数字失败: {}", e))?;

    println!("数字: {}", num);
    Ok(())
}

自定义错误类型

rust
#[derive(Debug)]
enum AppError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
    Validation(String),
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            AppError::Io(e) => write!(f, "IO 错误: {}", e),
            AppError::Parse(e) => write!(f, "解析错误: {}", e),
            AppError::Validation(s) => write!(f, "验证错误: {}", s),
        }
    }
}

impl std::error::Error for AppError {}