match, matches! 和 if let

match

  1. 🌟🌟
2. // 填空
3. enum Direction {
4. East,
5. West,
6. North,
7. South,
8. }

10. fn main() {
11. let dire = Direction::South;
12. match dire {
13. Direction::East => println!("East"),
14. __  => { // 在这里匹配 South 或 North
15. println!("South or North");
16. },
17. _ => println!(__),
18. };
19. }
  1. 🌟🌟 match 是一个表达式,因此可以用在赋值语句中
2. fn main() {
3. let boolean = true;

5. // 使用 match 表达式填空,并满足以下条件
6. //
7. // boolean = true => binary = 1
8. // boolean = false => binary = 0
9. let binary = __;

11. assert_eq!(binary, 1);
12. }
  1. 🌟🌟 使用 match 匹配出枚举成员持有的值
2. // 填空
3. enum Message {
4. Quit,
5. Move { x: i32, y: i32 },
6. Write(String),
7. ChangeColor(i32, i32, i32),
8. }

10. fn main() {
11. let msgs = [
12. Message::Quit,
13. Message::Move{x:1, y:3},
14. Message::ChangeColor(255,255,0)
15. ];

17. for msg in msgs {
18. show_message(msg)
19. }
20. }

22. fn show_message(msg: Message) {
23. match msg {
24. __ => { // 这里匹配 Message::Move
25. assert_eq!(a, 1);
26. assert_eq!(b, 3);
27. },
28. Message::ChangeColor(_, g, b) => {
29. assert_eq!(g, __);
30. assert_eq!(b, __);
31. }
32. __ => println!("no data in these variants")
33. }
34. }

matches!

matches! 看起来像 match, 但是它可以做一些特别的事情

  1. 🌟🌟
2. fn main() {
3. let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];

5. // 使用 `matches!` 填空
6. for ab in alphabets {
7. assert!(__)
8. }
9. }
  1. 🌟🌟
2. enum MyEnum {
3. Foo,
4. Bar
5. }

7. fn main() {
8. let mut count = 0;

10. let v = vec![MyEnum::Foo,MyEnum::Bar,MyEnum::Foo];
11. for e in v {
12. if e == MyEnum::Foo { // 修复错误,只能修改本行代码
13. count += 1;
14. }
15. }

17. assert_eq!(count, 2);
18. }

if let

在有些时候, 使用 match 匹配枚举有些太重了,此时 if let 就非常适合.

  1. 🌟
2. fn main() {
3. let o = Some(7);

5. // 移除整个 `match` 语句块,使用 `if let` 替代
6. match o {
7. Some(i) => {
8. println!("This is a really long string and `{:?}`", i);
9. }
10. _ => {}
11. };
12. }
  1. 🌟🌟
2. // 填空
3. enum Foo {
4. Bar(u8)
5. }

7. fn main() {
8. let a = Foo::Bar(1);

10. __ {
11. println!("foobar 持有的值是: {}", i);
12. }
13. }
  1. 🌟🌟
2. enum Foo {
3. Bar,
4. Baz,
5. Qux(u32)
6. }

8. fn main() {
9. let a = Foo::Qux(10);

11. // 移除以下代码,使用 `match` 代替
12. if let Foo::Bar = a {
13. println!("match foo::bar")
14. } else if let Foo::Baz = a {
15. println!("match foo::baz")
16. } else {
17. println!("match others")
18. }
19. }

变量遮蔽( Shadowing )

  1. 🌟🌟
2. // 就地修复错误
3. fn main() {
4. let age = Some(30);
5. if let Some(age) = age { // 创建一个新的变量,该变量与之前的 `age` 变量同名
6. assert_eq!(age, Some(30));
7. } // 新的 `age` 变量在这里超出作用域

9. match age {
10. // `match` 也能实现变量遮蔽
11. Some(age) =>  println!("age 是一个新的变量,它的值是 {}",age),
12. _ => ()
13. }
14. }

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