第 5 章:错误处理与测试

第 5 章:错误处理与测试

5.1 错误处理方式

Rust 主要提供两种错误处理模式:

  • panic!:不可恢复错误
  • Result<T, E>:可恢复错误
panic!("程序遇到致命错误");

Result

use std::fs::File;

fn read_file() -> Result<String, std::io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}
  • ? 运算符用于传播错误

5.2 自定义错误类型

use std::fmt;

#[derive(Debug)]
enum MyError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MyError::Io(err) => write!(f, "IO 错误: {}", err),
            MyError::Parse(err) => write!(f, "解析错误: {}", err),
        }
    }
}

5.3 测试基础

单元测试

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}
  • cargo test 运行测试
  • assert!, assert_eq!, assert_ne!

集成测试

集成测试放在 tests/ 目录下。

// tests/integration_test.rs
use my_crate;

#[test]
fn test_example() {
    assert_eq!(my_crate::add(2, 3), 5);
}

5.4 练习

  • 为一个函数编写单元测试
  • 添加一个返回 Result 的函数并处理错误
  • 创建一个集成测试来验证库 API
posted on 2026-05-09 21:58  小樊童鞋  阅读(3)  评论(0)    收藏  举报