学习目标
读完这一节,你会用 if let 只处理一种情况;while let 循环到匹配失败为止;let else 在不匹配时提前返回;给 match 分支加守卫;还会用到 @ 绑定。
上一节练习答案
上一节的练习:用枚举和 match 写一个算面积的程序——定义 Shape 枚举,写 area(&self) -> f64,match 算圆面积 πr²、矩形宽乘高、三角形海伦公式,main 里打印三个形状的面积,保留两位小数。
参考答案:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
Triangle { a: f64, b: f64, c: f64 },
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle { a, b, c } => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
fn main() {
let shapes = [
Shape::Circle(5.0),
Shape::Rectangle { width: 3.0, height: 4.0 },
Shape::Triangle { a: 3.0, b: 4.0, c: 5.0 },
];
for s in &shapes {
println!("面积:{:.2}", s.area());
}
}
|
运行结果:
1
2
3
| 面积:78.54
面积:12.00
面积:6.00
|
最后一问:area 的 match 不能漏变体,因为 match 要求穷尽所有情况。给 Shape 再加一个 Square(f64),这个 match 会立刻编译失败,直到补上正方形的分支。新情况出现时,编译器会追着你把所有处理它的地方都改掉,一个都漏不掉。
核心概念
if let:只关心一种情况
很多时候我们只关心一种情况:Option 只有 Some 才需要取值,None 一句话带过,写成 match 得两个分支,显得啰嗦。
if let 就是为这种情况准备的:只写你关心的那一个模式,匹配上了就执行,不匹配就走 else,语法是 if let 模式 = 值。只关心一种模式用 if let;要穷尽所有情况用 match。
1
2
3
4
5
| if let Some(n) = name {
println!("你好,{}", n);
} else {
println!("你好,陌生人");
}
|
while let:一直匹配到失败为止
while let 是 if let 的循环版:模式能匹配上就一直循环,匹配失败就停。 典型用法是不断“取”东西,取到空为止:
1
2
3
4
| let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("弹出:{}", top);
}
|
Vec::pop 在栈非空时返回 Some(元素),栈空了返回 None。while let Some(top) = stack.pop() 就是:每次循环先弹一个,弹到了就打印,弹不到就停。迭代器也一样,next() 返回 None 说明取完了。“取到就处理,取不到就停”直接写在循环条件里。
let else:不匹配就提前走人
函数开头要从 Option 里取出值,取不到就直接返回,let else 是最直接的写法:
1
2
3
4
| let Some(mode) = config else {
return "默认模式";
};
// 到这里,mode 一定是取出来的值
|
let else 读作“取出来,否则就……”。匹配上了,mode 就是里面的值;匹配不上,就执行 else 块——这个块必须以 return、break 或 panic! 这类发散方式结束,也就是不匹配就别往下走,这样 let else 之后的 mode 一定存在。
let else 是 Rust 1.65 加入的稳定功能,把“取不到就走人”写在函数开头,后面的代码不用再缩进一层,也不用到处 unwrap。
守卫:给分支加条件
match 的模式只能比形状——是哪个变体、值在哪个范围。但有时候还要看值满不满足条件,比如“正偶数”和“正奇数”都是正数,模式分不开。这时候用守卫(guard):模式后面写 if 条件,模式和条件都过了,分支才命中:
1
2
3
4
5
6
| match n {
x if x < 0 => "负数",
0 => "零",
x if x % 2 == 0 => "正偶数",
_ => "正奇数",
}
|
编译器从上往下试,先看模式,再看守卫。n = 4 时,前两个分支过不去,第三个分支模式和守卫都过了,命中;n = 7 落到 _。
守卫有个重要限制:带守卫的分支不算进穷尽性检查。编译器不知道守卫运行时是真是假,哪怕你把所有情况都用守卫列了一遍,还是必须补一个 _ 兜底。
守卫也可以用在枚举的变体上:
1
2
3
4
5
6
| match shape {
Shape::Circle(r) if *r > 10.0 => "大圆",
Shape::Circle(r) => "小圆",
Shape::Rectangle { width, height } if width == height => "正方形",
Shape::Rectangle { width, height } => "矩形",
}
|
注意第一个分支写的是 *r:shape 是 &Shape,r 是 &f64。
@ 绑定与 | 合并:模式里的小工具
最后补两个小工具。@ 绑定:在比对范围的同时,把值也绑下来。比如判断一个数在 1 到 10 之间,还想把它打印出来:
1
2
3
4
| match x {
n @ 1..=10 => println!("{} 在 1 到 10 之间", n),
_ => println!("不在 1 到 10 之间"),
}
|
没有 @,模式 1..=10 只能判断范围,拿不到具体是几;有了 n @,两件事一次办完。| 合并:多个模式走同一个分支,用竖线连起来:
1
2
3
4
| match dir {
Direction::North | Direction::South => "南北向",
Direction::East | Direction::West => "东西向",
}
|
| 要求所有模式绑定的变量一致:两边绑定的变量要同名同类型。
放在一起看:match 穷尽所有情况;if let 只取一种;while let 取到没有为止;let else 取不到就走人;守卫和 @ 是模式不够用时的补充。
可运行代码
第一个程序:if let 与 let else:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| fn greet(name: Option<&str>) {
if let Some(n) = name {
println!("你好,{}", n);
} else {
println!("你好,陌生人");
}
}
fn get_mode(config: Option<&str>) -> &str {
let Some(mode) = config else {
return "默认模式";
};
mode
}
fn main() {
greet(Some("小优"));
greet(None);
let score = Some(92);
if let Some(s) = score {
println!("分数是 {}", s);
}
println!("当前模式:{}", get_mode(Some("debug")));
println!("当前模式:{}", get_mode(None));
}
|
运行结果:
1
2
3
4
5
| 你好,小优
你好,陌生人
分数是 92
当前模式:debug
当前模式:默认模式
|
注意分号:let else 是一条语句,分号不能少。
第二个程序:while let 弹出栈顶和取迭代器元素:
1
2
3
4
5
6
7
8
9
10
11
12
| fn main() {
let mut stack = vec![1, 2, 3, 4, 5];
while let Some(top) = stack.pop() {
println!("弹出:{}", top);
}
println!("栈空了");
let mut nums = vec![10, 20, 30].into_iter();
while let Some(n) = nums.next() {
println!("取到:{}", n);
}
}
|
运行结果:
1
2
3
4
5
6
7
8
9
| 弹出:5
弹出:4
弹出:3
弹出:2
弹出:1
栈空了
取到:10
取到:20
取到:30
|
栈后进先出,弹出 5、4、3、2、1;迭代器按顺序取 10、20、30。
第三个程序:守卫给数字分类,分支顺序就是判断顺序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| fn classify(n: i32) -> &'static str {
match n {
x if x < 0 => "负数",
0 => "零",
x if x % 2 == 0 => "正偶数",
_ => "正奇数",
}
}
fn main() {
for n in [-3, 0, 4, 7, 10] {
println!("{}:{}", n, classify(n));
}
}
|
运行结果:
1
2
3
4
5
| -3:负数
0:零
4:正偶数
7:正奇数
10:正偶数
|
删掉 0 => "零" 试试:0 会落到正偶数分支——0 是偶数,但“零”这个说法就没了。
第四个程序:守卫用在枚举上,再加 @ 绑定:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| #[derive(Debug)]
enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
}
fn describe(shape: &Shape) -> String {
match shape {
Shape::Circle(r) if *r > 10.0 => format!("大圆,半径 {}", r),
Shape::Circle(r) => format!("小圆,半径 {}", r),
Shape::Rectangle { width, height } if width == height => {
format!("正方形,边长 {}", width)
}
Shape::Rectangle { width, height } => {
format!("矩形,{} × {}", width, height)
}
}
}
fn main() {
let shapes = [
Shape::Circle(5.0),
Shape::Circle(12.0),
Shape::Rectangle { width: 3.0, height: 4.0 },
Shape::Rectangle { width: 5.0, height: 5.0 },
];
for s in &shapes {
println!("{:?} -> {}", s, describe(s));
}
// @ 绑定:既比对范围,又把值留下来用
let x = 7;
match x {
n @ 1..=10 => println!("{} 在 1 到 10 之间", n),
_ => println!("不在 1 到 10 之间"),
}
}
|
运行结果:
1
2
3
4
5
| Circle(5.0) -> 小圆,半径 5
Circle(12.0) -> 大圆,半径 12
Rectangle { width: 3.0, height: 4.0 } -> 矩形,3 × 4
Rectangle { width: 5.0, height: 5.0 } -> 正方形,边长 5
7 在 1 到 10 之间
|
常见坑
- 用
if let 却忘了 else:None 没处理,逻辑上就漏了一个分支——if let 不强制穷尽,编译器不提醒。 while let 里忘了推进:循环体里没让值发生变化(比如一直 peek 不 pop),就是死循环。let else 的 else 块里没有发散:必须以 return、break、continue 或 panic! 结尾,写普通语句就编不过。- 守卫当穷尽性:
x if x > 0 和 x if x <= 0 两个分支,以为覆盖了所有整数,编译器不认——守卫不参与穷尽性检查,必须补 _。 - 守卫里用了移动的值:模式绑定移动了值,守卫里再用原来的值就编不过;只想看一眼就用引用匹配。
@ 绑定写反方向:1..=10 @ n 是错的,绑定名在前:n @ 1..=10。
动手练习
写一个“成绩单处理”程序:
grade(score: Option<u32>) -> &'static str:if let 取出分数;Some 时 match 加守卫评级(90 以上优秀,80–89 良好,60–79 及格,60 以下不及格);None 返回“缺考”。first_pass(scores: &[u32]) -> Option<u32>:while let 配迭代器,返回第一个及格(≥60)的分数,没有返回 None。main 里测试 grade(Some(95))、grade(Some(72))、grade(None),以及 first_pass(&[45, 58, 61, 90])、first_pass(&[30, 40])。- 回答:
grade 为什么用 if let 不用 match?while let 怎么知道该停?
提示:next() 每次取一个 Some(&u32),模式写 Some(&n)。
小结与预告
核心就一句话:match 穷尽所有情况;if let 只取一种,while let 取到没有为止,let else 取不到就走人,模式不够细就加守卫和 @ 绑定。
下一节 7.1:Option——告别空指针。上一节见过它,这一节的 if let 和 while let 也都是拿它练的手,下一节讲透它的常用方法,以及 unwrap 什么时候能用。
配套练习:在学习站动手练这一节
本文代码基于 Rust 1.8x / Edition 2024 验证。