Rust错误处理:Result与Option类型完全指南
3 阅读
预计 3 分钟
Rust通过类型系统强制处理错误,而非依赖异常。本文详解Result和Option两大核心类型。
## Option类型
Option用于表示可能为空的值:
```rust
fn find_user(id: u32) -> Option {
if id == 1 {
Some(String::from("Alice"))
} else {
None
}
}
match find_user(1) {
Some(name) => println!("Found: {}", name),
None => println!("Not found"),
}
```
## Result类型
Result用于可能失败的操作:
```rust
use std::fs::File;
use std::io;
fn read_file(path: &str) -> Result {
let content = std::fs::read_to_string(path)?;
Ok(content)
}
```
## ?运算符
?运算符简化错误传播:
```rust
fn read_config() -> Result {
let content = std::fs::read_to_string("config.toml")?;
let config: Config = toml::from_str(&content)?;
Ok(config)
}
```
## thiserror与anyhow
对于库代码推荐thiserror,应用代码推荐anyhow:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Parse error: {0}")]
Parse(#[from] std::num::ParseIntError),
}
use anyhow::{Context, Result};
fn process() -> Result<()> {
let data = std::fs::read_to_string("data.txt")
.context("Failed to read data file")?;
Ok(())
}
```
Rust的错误处理虽然初学时感觉繁琐,但它确保你不会遗漏任何错误情况,大大提高了代码的可靠性。
0 条评论 欢迎参与讨论