# 15. Option 与 Result ## 学习目标 - 理解 `Option` 的语义和使用场景。 - 理解 `Result` 的语义和使用场景。 - 掌握常见的组合子方法:`map`、`unwrap_or`、`unwrap`、`expect` 等。 - 初步认识 `?` 操作符。 ## 15.1 为什么需要 Option 在许多语言中,空值(null)是万恶之源。Rust 没有 null,而是用 `Option` 显式表达“值可能存在或不存在”: ```rust enum Option { Some(T), None, } ``` 它已经在标准库预定义,可以直接使用: ```rust fn main() { let some_number = Some(5); let some_string = Some(String::from("hello")); let absent_number: Option = None; } ``` ## 15.2 Option 与 T 不能直接混用 `Option` 和 `T` 是不同类型。Rust 不允许你像 null 一样直接假设它里面有值: ```rust fn main() { let x: i8 = 5; let y: Option = Some(5); let sum = x + y; // 错误:不能直接把 i8 和 Option 相加 } ``` 必须先把 `Option` 转换成 `T` 或处理 `None` 的情况。 ## 15.3 使用 match 处理 Option ```rust fn plus_one(x: Option) -> Option { match x { None => None, Some(i) => Some(i + 1), } } fn main() { let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` `match` 是处理 `Option` 最常用的方式,因为编译器会强制你处理 `None`。 ## 15.4 常用组合子 ### `map` 对 `Some` 内部的值做转换,如果为 `None` 则保持 `None`: ```rust fn main() { let x: Option = Some(5); let y = x.map(|v| v + 1); // Some(6) } ``` ### `unwrap_or` 如果是 `Some`,返回值;如果是 `None`,返回默认值: ```rust fn main() { let x: Option = None; let v = x.unwrap_or(0); // 0 } ``` ### `unwrap` 与 `expect` `unwrap` 会直接取出 `Some` 的值,如果是 `None` 则 panic: ```rust let x: Option = Some(5); let v = x.unwrap(); // 5 ``` `expect` 与 `unwrap` 类似,但可以附带自定义错误信息: ```rust let v = x.expect("x 必须有值"); ``` > 在正式代码中,除非确定不可能是 `None`,否则尽量避免使用 `unwrap`。 ## 15.5 Result `Result` 用于表示可能失败的操作: ```rust enum Result { Ok(T), Err(E), } ``` 例如文件打开可能失败: ```rust use std::fs::File; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => { panic!("打开文件失败: {:?}", error); } }; } ``` ## 15.6 Result 的常用组合子 ### `map` 与 `map_err` ```rust let result = File::open("hello.txt").map(|file| { // 对成功结果做处理 file }); ``` ### `unwrap_or` 和 `unwrap_or_else` ```rust let f = File::open("hello.txt").unwrap_or_else(|error| { println!("打开失败: {:?}", error); // 创建默认文件 File::create("hello.txt").unwrap() }); ``` ## 15.7 ? 操作符初识 `?` 操作符可以简化 `Result` 的错误传递: ```rust use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } ``` 如果 `?` 前面的表达式是 `Err`,函数会立即返回该错误;如果是 `Ok`,则解出其中的值。后续阶段会详细展开。 ## 15.8 小结 | 类型 | 含义 | 典型场景 | | `Option` | 可能有值,也可能没有 | 查找、配置项、可选参数 | | `Result` | 操作可能成功,也可能失败 | 文件 IO、网络、解析 | | `unwrap` | 强制取值,失败则 panic | 快速原型、确定不会失败时 | | `?` | 自动传播错误 | 函数返回 `Result` 时 | ## 15.9 思考题 1. 为什么 Rust 不直接允许 `Option` 与 `i8` 相加? 2. 写一段代码,尝试读取一个文件。如果文件不存在,返回 `None`;存在则返回 `Some(String)`。 3. 什么时候应该使用 `unwrap_or`,什么时候应该使用 `match`?