Rust 在 Debian 上的错误处理技巧
一 基础范式与最小示例
use std::fs;
use std::io;
fn read_file(path: &str) -> Result<String, io::Error> {
let s = fs::read_to_string(path)?;
Ok(s)
}
fn main() {
match read_file("config.toml") {
Ok(c) => println!("config: {}", c),
Err(e) => eprintln!("read error: {}", e),
}
}
以上要点与示例适用于 Debian 环境,因为 Rust 的错误处理是语言特性,与操作系统无关。
二 自定义错误与错误组合
use thiserror::Error;
use std::io;
use std::num::ParseIntError;
#[derive(Error, Debug)]
enum AppError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Parse error: {0}")]
Parse(#[from] ParseIntError),
}
fn parse_config(path: &str) -> Result<i32, AppError> {
let s = fs::read_to_string(path)?; // Io 自动转为 AppError::Io
let n: i32 = s.trim().parse()?; // ParseIntError 转为 AppError::Parse
Ok(n)
}
当项目需要区分多种错误来源并进行组合或包装时,上述模式更易于维护与测试。
三 在 Debian 上的常见陷阱与修复
sudo apt-get update
sudo apt-get install build-essential libssl-dev libsqlite3-dev libpq-dev
cargo build
上述依赖安装与错误表现均在 Debian/Ubuntu 等发行版中广泛验证。
四 错误日志与调试技巧
use log::{error, info};
fn main() {
env_logger::init();
if let Err(e) = run() {
error!("run failed: {}", e);
}
}
运行程序时设置环境变量:RUST_LOG=info cargo run。
rust-gdb target/debug/your_program
# 或
rust-lldb target/debug/your_program
valgrind --tool=memcheck target/debug/your_program
日志与调试工具在 Debian 上的使用方式与在其他 Linux 发行版一致,可显著提升错误定位效率。
五 工程化最佳实践
rustup component add rustfmt
cargo fmt
rustup component add clippy
cargo clippy