Z
ZHANK
模式匹配与错误

模式匹配深入

match 守卫 if、if let/while let、@ 绑定、ref/destructure

模式匹配深入

match 穷举、if let 简洁、while let 循环——Rust 的模式匹配是语言特性而非库。

学完本章你将: 掌握 match 守卫、if let/while let、@ 绑定、解构。


match 守卫

rust
let num = Some(4);

match num {
    Some(x) if x < 5 => println!("小于 5: {}", x),
    Some(x) => println!("大于等于 5: {}", x),
    None => println!("没有值"),
}

if let —— 只关心一种情况

rust
let config_max = Some(3u8);

// match 全写(啰嗦)
match config_max {
    Some(max) => println!("max = {}", max),
    _ => (),
}

// if let 简写(推荐)
if let Some(max) = config_max {
    println!("max = {}", max);
}

// if let + else
if let Some(max) = config_max {
    println!("有值: {}", max);
} else {
    println!("没有值");
}

解构

rust
// 结构体解构
let p = Point { x: 0, y: 7 };
let Point { x, y } = p;
let Point { x: a, y: b } = p;  // 重命名

// match 中解构
match p {
    Point { x, y: 0 } => println!("在 x 轴上, x = {}", x),
    Point { x: 0, y } => println!("在 y 轴上, y = {}", y),
    Point { x, y } => println!("({}, {})", x, y),
}

// @ 绑定
match num {
    n @ 1..=5 => println!("1-5 之间: {}", n),
    n @ 6..=10 => println!("6-10 之间: {}", n),
    _ => println!("其他"),
}