Option<T> 的语义和使用场景。Result<T, E> 的语义和使用场景。map、unwrap_or、unwrap、expect 等。? 操作符。
在许多语言中,空值(null)是万恶之源。Rust 没有 null,而是用 Option<T> 显式表达“值可能存在或不存在”:
enum Option<T> { Some(T), None, }
它已经在标准库预定义,可以直接使用:
fn main() { let some_number = Some(5); let some_string = Some(String::from("hello")); let absent_number: Option<i32> = None; }
Option<T> 和 T 是不同类型。Rust 不允许你像 null 一样直接假设它里面有值:
fn main() { let x: i8 = 5; let y: Option<i8> = Some(5); let sum = x + y; // 错误:不能直接把 i8 和 Option<i8> 相加 }
必须先把 Option<T> 转换成 T 或处理 None 的情况。
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。
对 Some 内部的值做转换,如果为 None 则保持 None:
fn main() { let x: Option<i32> = Some(5); let y = x.map(|v| v + 1); // Some(6) }
如果是 Some,返回值;如果是 None,返回默认值:
fn main() { let x: Option<i32> = None; let v = x.unwrap_or(0); // 0 }
unwrap 会直接取出 Some 的值,如果是 None 则 panic:
let x: Option<i32> = Some(5); let v = x.unwrap(); // 5
expect 与 unwrap 类似,但可以附带自定义错误信息:
let v = x.expect("x 必须有值");
在正式代码中,除非确定不可能是 `None`,否则尽量避免使用 `unwrap`。
## 15.5 Result<T, E>
Result 用于表示可能失败的操作:
enum Result<T, E> { Ok(T), Err(E), }
例如文件打开可能失败:
use std::fs::File; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => { panic!("打开文件失败: {:?}", error); } }; }
let result = File::open("hello.txt").map(|file| { // 对成功结果做处理 file });
let f = File::open("hello.txt").unwrap_or_else(|error| { println!("打开失败: {:?}", error); // 创建默认文件 File::create("hello.txt").unwrap() });
? 操作符可以简化 Result 的错误传递:
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,则解出其中的值。后续阶段会详细展开。
| 类型 | 含义 | 典型场景 |
Option<T> | 可能有值,也可能没有 | 查找、配置项、可选参数 |
Result<T, E> | 操作可能成功,也可能失败 | 文件 IO、网络、解析 |
unwrap | 强制取值,失败则 panic | 快速原型、确定不会失败时 |
? | 自动传播错误 | 函数返回 Result 时 |
Option<i8> 与 i8 相加?
None;存在则返回 Some(String)。
unwrap_or,什么时候应该使用 match?