Consider the following Rust code snippet. What will it print?
let x = Some(5); match x { Some(n) if n > 3 => println!("Greater than 3: {}", n), Some(n) => println!("Some number: {}", n), None => println!("No value"), }
Look at the if guard in the first arm and the value inside Some.
The match arm with Some(n) if n > 3 matches because n is 5, which is greater than 3. So it prints "Greater than 3: 5".
Analyze the nested match expression below. What will be printed?
let value = (2, Some(4)); match value { (x, Some(y)) if x == y => println!("Equal: {}" , x), (x, Some(y)) => println!("Not equal: {} and {}", x, y), _ => println!("No match"), }
Check the tuple values and the if guard condition.
The tuple is (2, Some(4)). The first arm checks if x == y, but 2 != 4, so it skips. The second arm matches and prints "Not equal: 2 and 4".
Consider this Rust code using ref and variable shadowing in a match. What will it print?
let x = 5; match x { ref r => println!("Got a reference to {}", r), }
Remember that ref creates a reference to the matched value.
The pattern ref r binds r as a reference to x. Printing {} with r dereferences automatically, so it prints "Got a reference to 5".
What will this Rust code print?
let num = 7; match num { 1 | 3 | 5 | 7 | 9 => println!("Odd number"), 2..=8 => println!("Between 2 and 8"), _ => println!("Other number"), }
Check the order of patterns and which one matches first.
The number 7 matches the first arm because 7 is listed explicitly as an odd number. Match arms are checked top to bottom, so it prints "Odd number".
Given the following Rust enums and match, what will be printed?
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } let msg = Message::Move { x: 10, y: 20 }; match msg { Message::Move { x, y } if x == y => println!("Move diagonally to ({}, {})", x, y), Message::Move { x, y } => println!("Move to ({}, {})", x, y), Message::Write(text) => println!("Text message: {}", text), Message::Quit => println!("Quit message"), _ => println!("Other message"), }
Look carefully at the if guard condition and the values of x and y.
The message is Move { x: 10, y: 20 }. The first arm matches only if x == y, which is false here. So the second arm matches and prints "Move to (10, 20)".