Appearance
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 | 基础 | ✅ |
| 08 | Option与Result | ✅ |
| 09 | 泛型 | ⬜ |
