Skip to content

Day 08 - Option与Result

Option

rust
fn find_user(id: u32) -> Option<String> {
    if id == 1 {
        Some(String::from("alice"))
    } else {
        None
    }
}

// 使用
match find_user(1) {
    Some(name) => println!("Found: {}", name),
    None => println!("Not found"),
}

Result

rust
use std::fs::File;

fn read_file(path: &str) -> Result<String, std::io::Error> {
    let mut content = String::new();
    File::open(path)?. .read_to_string(&mut content)?;
    Ok(content)
}

问号运算符

rust
fn read_file(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;  // ?自动传播错误
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

📅 学习进度

Day主题状态
01-07基础
08Option与Result
09泛型

本文为Rust 30天学习计划第8天内容

📚 导航

| ← Day 07 - 上一章 | Day 09 - 下一章 →

最后更新: