目录

15. Option 与 Result

学习目标

15.1 为什么需要 Option<T>

在许多语言中,空值(null)是万恶之源。Rust 没有 null,而是用 Option<T> 显式表达“值可能存在或不存在”:

snippet.rust
enum Option<T> {
    Some(T),
    None,
}

它已经在标准库预定义,可以直接使用:

snippet.rust
fn main() {
    let some_number = Some(5);
    let some_string = Some(String::from("hello"));
    let absent_number: Option<i32> = None;
}

15.2 Option 与 T 不能直接混用

Option<T> 和 T 是不同类型。Rust 不允许你像 null 一样直接假设它里面有值:

snippet.rust
fn main() {
    let x: i8 = 5;
    let y: Option<i8> = Some(5);
 
    let sum = x + y; // 错误:不能直接把 i8 和 Option<i8> 相加
}

必须先把 Option<T> 转换成 T 或处理 None 的情况。

15.3 使用 match 处理 Option

snippet.rust
fn plus_one(x: Option<i32>) -> Option<i32> {
    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:

snippet.rust
fn main() {
    let x: Option<i32> = Some(5);
    let y = x.map(|v| v + 1); // Some(6)
}

`unwrap_or`

如果是 Some,返回值;如果是 None,返回默认值:

snippet.rust
fn main() {
    let x: Option<i32> = None;
    let v = x.unwrap_or(0); // 0
}

`unwrap` 与 `expect`

unwrap 会直接取出 Some 的值,如果是 None 则 panic:

snippet.rust
let x: Option<i32> = Some(5);
let v = x.unwrap(); // 5

expect 与 unwrap 类似,但可以附带自定义错误信息:

snippet.rust
let v = x.expect("x 必须有值");
在正式代码中,除非确定不可能是 `None`,否则尽量避免使用 `unwrap`。

## 15.5 Result<T, E>

Result 用于表示可能失败的操作:

snippet.rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

例如文件打开可能失败:

snippet.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`

snippet.rust
let result = File::open("hello.txt").map(|file| {
    // 对成功结果做处理
    file
});

`unwrap_or` 和 `unwrap_or_else`

snippet.rust
let f = File::open("hello.txt").unwrap_or_else(|error| {
    println!("打开失败: {:?}", error);
    // 创建默认文件
    File::create("hello.txt").unwrap()
});

15.7 ? 操作符初识

? 操作符可以简化 Result 的错误传递:

snippet.rust
use std::fs::File;
use std::io;
use std::io::Read;
 
fn read_username_from_file() -> Result<String, io::Error> {
    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<T> 可能有值,也可能没有 查找、配置项、可选参数
Result<T, E> 操作可能成功,也可能失败 文件 IO、网络、解析
unwrap 强制取值,失败则 panic 快速原型、确定不会失败时
? 自动传播错误 函数返回 Result 时

15.9 思考题

  1. 为什么 Rust 不直接允许 Option<i8> 与 i8 相加?
  2. 写一段代码,尝试读取一个文件。如果文件不存在,返回 None;存在则返回 Some(String)。
  3. 什么时候应该使用 unwrap_or,什么时候应该使用 match?