跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Rust Result枚举
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
{{DISPLAYTITLE:Rust Result枚举}} '''Rust Result枚举'''是Rust标准库中用于错误处理的核心类型之一,它表示一个操作可能成功(包含结果值)或失败(包含错误信息)。与`Option`类型不同,`Result`专门设计用于显式处理错误场景,是Rust“安全优先”理念的重要体现。 == 基本定义 == `Result`枚举在标准库中的定义如下: <syntaxhighlight lang="rust"> #[derive(Debug, PartialEq, Clone, Copy)] pub enum Result<T, E> { Ok(T), Err(E), } </syntaxhighlight> 其中: * `T` 表示成功时返回的值的类型 * `E` 表示错误时返回的错误类型 == 核心特性 == === 模式匹配处理 === 最基础的使用方式是通过`match`表达式处理: <syntaxhighlight lang="rust"> fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { Err(String::from("Cannot divide by zero")) } else { Ok(a / b) } } fn main() { match divide(10.0, 2.0) { Ok(result) => println!("Result: {}", result), Err(e) => println!("Error: {}", e), } } </syntaxhighlight> '''输出:''' <pre> Result: 5 </pre> === 组合方法 === `Result`提供了一系列组合方法: {| class="wikitable" |+ 常用组合方法 ! 方法 !! 描述 !! 等效代码 |- | <code>unwrap()</code> || 成功时返回值,失败时panic || <code>match self { Ok(t) => t, Err(e) => panic!() }</code> |- | <code>unwrap_or(default)</code> || 成功时返回值,失败时返回默认值 || <code>match self { Ok(t) => t, Err(_) => default }</code> |- | <code>map(f)</code> || 对成功值应用函数 || <code>match self { Ok(t) => Ok(f(t)), Err(e) => Err(e) }</code> |- | <code>and_then(f)</code> || 链式操作(类似flatMap) || <code>match self { Ok(t) => f(t), Err(e) => Err(e) }</code> |} == 错误传播 == Rust提供了`?`操作符简化错误传播: <syntaxhighlight lang="rust"> use std::fs::File; fn read_file() -> Result<String, std::io::Error> { let mut file = File::open("hello.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } </syntaxhighlight> 等价于: <syntaxhighlight lang="rust"> match File::open("hello.txt") { Ok(mut file) => { match file.read_to_string(&mut contents) { Ok(_) => Ok(contents), Err(e) => Err(e), } } Err(e) => Err(e), } </syntaxhighlight> == 实际应用案例 == === 文件处理 === <syntaxhighlight lang="rust"> use std::fs; use std::io; fn read_config() -> Result<String, io::Error> { let config = fs::read_to_string("config.toml")?; Ok(config) } fn main() { match read_config() { Ok(config) => println!("Config loaded: {}", config), Err(e) => println!("Error reading config: {}", e), } } </syntaxhighlight> === 网络请求 === <syntaxhighlight lang="rust"> use reqwest::blocking::get; fn fetch_data(url: &str) -> Result<String, reqwest::Error> { let response = get(url)?; response.text() } fn main() { match fetch_data("https://api.example.com/data") { Ok(data) => println!("Data received: {}", data), Err(e) => println!("Request failed: {}", e), } } </syntaxhighlight> == 高级用法 == === 自定义错误类型 === 通过实现`std::error::Error` trait创建自定义错误: <syntaxhighlight lang="rust"> #[derive(Debug)] enum MyError { Io(std::io::Error), Parse(std::num::ParseIntError), } impl From<std::io::Error> for MyError { fn from(err: std::io::Error) -> MyError { MyError::Io(err) } } fn process_file() -> Result<i32, MyError> { let contents = std::fs::read_to_string("data.txt")?; let num = contents.trim().parse::<i32>()?; Ok(num * 2) } </syntaxhighlight> === 错误转换 === 使用`map_err`进行错误类型转换: <syntaxhighlight lang="rust"> fn string_length(s: &str) -> Result<usize, String> { s.parse::<i32>() .map(|n| n as usize) .map_err(|e| format!("Parse failed: {}", e)) } </syntaxhighlight> == 可视化流程 == <mermaid> graph TD A[开始操作] --> B{是否成功?} B -->|成功| C[返回 Ok(value)] B -->|失败| D[返回 Err(error)] C --> E[继续处理值] D --> F[处理错误或传播] </mermaid> == 数学表示 == Result类型可以形式化表示为: <math> \text{Result}(T,E) = \text{Ok}(T) \cup \text{Err}(E) </math> 其中: * <math>\text{Ok}(T)</math> 表示成功情况 * <math>\text{Err}(E)</math> 表示错误情况 == 最佳实践 == 1. 优先使用`?`操作符而非`unwrap()` 2. 为库代码定义具体的错误类型 3. 使用`thiserror`或`anyhow`等库简化错误处理 4. 在应用程序入口处统一处理错误 5. 为错误实现`std::error::Error` trait == 参见 == * Rust Option枚举 * Rust错误处理机制 * Rust trait系统 [[Category:Rust编程语言]] [[Category:Rust数据结构]] [[Category:错误处理]] [[Category:编程语言]] [[Category:Rust]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)