Patterns

  1. 🌟🌟 Use | to match several values, use ..= to match an inclusive range.
2. fn main() {}
3. fn match_number(n: i32) {
4. match n {
5. // Match a single value
6. 1 => println!("One!"),
7. // Fill in the blank with `|`, DON'T use `..` or `..=`
8. __ => println!("match 2 -> 5"),
9. // Match an inclusive range
10. 6..=10 => {
11. println!("match 6 -> 10")
12. },
13. _ => {
14. println!("match -infinite -> 0 or 11 -> +infinite")
15. }
16. }
17. }
  1. 🌟🌟🌟 The @ operator lets us create a variable that holds a value, at the same time we are testing that value to see whether it matches a pattern.
2. struct Point {
3. x: i32,
4. y: i32,
5. }

7. fn main() {
8. // Fill in the blank to let p match the second arm
9. let p = Point { x: __, y: __ };

11. match p {
12. Point { x, y: 0 } => println!("On the x axis at {}", x),
13. // Second arm
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. // Fix the errors
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!("Found an id in range [3, 7]: {}", id),
14. Message::Hello { id: newid@10 | 11 | 12 } => {
15. println!("Found an id in another range [10, 12]: {}", newid)
16. }
17. Message::Hello { id } => println!("Found some other id: {}", id),
18. }
19. }
  1. 🌟🌟 A match guard is an additional if condition specified after the pattern in a match arm that must also match, along with the pattern matching, for that arm to be chosen.
2. // Fill in the blank to make the code work, `split` MUST be used
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. }

12. println!("Success!");
13. }
  1. 🌟🌟 Ignoring remaining parts of the value with ..
2. // Fill the blank to make the code work
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. }

13. println!("Success!");
14. }
  1. 🌟🌟 Using pattern &mut V to match a mutable reference requires you to be very careful, due to V being a value after matching.
2. // FIX the error with least changing
3. // DON'T remove any code line
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. }

You can find the solutions here(under the solutions path), but only use it when you need it