Z
ZHANK
复合类型

Option 与 Result

Option<T> unwrap/map/and_then、Result<T,E> 错误处理、? 传播

Option 与 Result

Option<T> 表示"可能有值",Result<T, E> 表示"可能失败"——Rust 用类型系统替代 null 和异常。

学完本章你将: 掌握 Option unwrap/map/and_then、Result/? 传播、组合子。


Option 常用方法

rust
fn main() {
    let x: Option<i32> = Some(42);
    let y: Option<i32> = None;

    // unwrap —— 取值(None 会 panic)
    x.unwrap();  // 42

    // unwrap_or —— 给默认值
    y.unwrap_or(0);  // 0

    // map —— 有值时转换
    x.map(|n| n * 2);  // Some(84)

    // and_then —— 链式调用
    x.and_then(|n| if n > 0 { Some(n * 2) } else { None });
}

Result

rust
use std::fs::File;
use std::io::Read;

fn read_file(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;     // ? = 错误时立即返回
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() {
    match read_file("hello.txt") {
        Ok(contents) => println!("{}", contents),
        Err(e) => println!("读取失败: {}", e),
    }

    // 简写
    let contents = read_file("hello.txt").unwrap_or_default();
}

? 运算符

rust
// ? 等价于:
// match result {
//     Ok(v) => v,
//     Err(e) => return Err(e.into()),
// }

// 可以在返回 Result 或 Option 的函数中使用
fn first_even(nums: &[i32]) -> Option<&i32> {
    nums.iter().find(|&&n| n % 2 == 0)  // 返回 Option<&i32>
}