模式

  1. 🌟🌟 使用 | 可以匹配多个值, 而使用 ..= 可以匹配一个闭区间的数值序列
2. fn main() {}
3. fn match_number(n: i32) {
4. match n {
5. // 匹配一个单独的值
6. 1 => println!("One!"),
7. // 使用 `|` 填空,不要使用 `..` 或 `..=`
8. __ => println!("match 2 -> 5"),
9. // 匹配一个闭区间的数值序列
10. 6..=10 => {
11. println!("match 6 -> 10")
12. },
13. _ => {
14. println!("match 11 -> +infinite")
15. }
16. }
17. }
  1. 🌟🌟🌟 @ 操作符可以让我们将一个与模式相匹配的值绑定到新的变量上
2. struct Point {
3. x: i32,
4. y: i32,
5. }

7. fn main() {
8. // 填空,让 p 匹配第二个分支
9. let p = Point { x: __, y: __ };

11. match p {
12. Point { x, y: 0 } => println!("On the x axis at {}", x),
13. // 第二个分支
14. Point { x: 0..=5, y: y@ (10 | 20 | 30) } => println!("On the y axis at {}", y),
15. Point { x, y } => println!("On neither axis: ({}, {})", x, y),
16. }
17. }
  1. 🌟🌟🌟
2. // 修复错误
3. enum Message {
4. Hello { id: i32 },
5. }

7. fn main() {
8. let msg = Message::Hello { id: 5 };

10. match msg {
11. Message::Hello {
12. id:  3..=7,
13. } => println!("id 值的范围在 [3, 7] 之间: {}", id),
14. Message::Hello { id: newid@10 | 11 | 12 } => {
15. println!("id 值的范围在 [10, 12] 之间: {}", newid)
16. }
17. Message::Hello { id } => println!("Found some other id: {}", id),
18. }
19. }
  1. 🌟🌟 匹配守卫(match guard)是一个位于 match 分支模式之后的额外 if 条件,它能为分支模式提供更进一步的匹配条件。
2. // 填空让代码工作,必须使用 `split`
3. fn main() {
4. let num = Some(4);
5. let split = 5;
6. match num {
7. Some(x) __ => assert!(x < split),
8. Some(x) => assert!(x >= split),
9. None => (),
10. }
11. }
  1. 🌟🌟🌟 使用 .. 忽略一部分值
2. // 填空,让代码工作
3. fn main() {
4. let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);

6. match numbers {
7. __ => {
8. assert_eq!(first, 2);
9. assert_eq!(last, 2048);
10. }
11. }
12. }
  1. 🌟🌟 使用模式 &mut V 去匹配一个可变引用时,你需要格外小心,因为匹配出来的 V 是一个值,而不是可变引用
2. // 修复错误,尽量少地修改代码
3. // 不要移除任何代码行
4. fn main() {
5. let mut v = String::from("hello,");
6. let r = &mut v;

8. match r {
9. &mut value => value.push_str(" world!")
10. }
11. }

你可以在这里找到答案(在 solutions 路径下)