The match statement in Rust is a powerful control flow operator that allows you to compare a value against a series of patterns and execute code based on which pattern matches. It's similar to switch statements in other languages but more powerful.
match value {
pattern1 => expression1,
pattern2 => expression2,
_ => default_expression,
}
let number = 13;
match number {
1 => println!("One"),
2 | 3 | 5 | 7 | 11 | 13 => println!("This is a prime"),
_ => println!("Not a prime"),
}
let point = (0, 0);
match point {
(0, 0) => println!("Origin"),
(0, y) => println!("Y axis, y = {}", y),
(x, 0) => println!("X axis, x = {}", x),
(x, y) => println!("Point: ({}, {})", x, y),
}
let arr = &[1, 2, 3];
match arr {
&[] => println!("Empty array"),
&[x] => println!("Single element: {}", x),
&[x, y] => println!("Two elements: {} {}", x, y),
&[x, .., z] => println!("Array with first {} and last {}", x, z),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
let msg = Message::Move { x: 3, y: 4 };
match msg {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Text message: {}", text),
}
let reference = &4;
match reference {
&val => println!("Got a value: {}", val),
}
// Reference matching with dereferencing
match *reference {
val => println!("Got a value: {}", val),
}
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 7 };
match point {
Point { x: 0, y } => println!("On y axis: {}", y),
Point { x, y: 0 } => println!("On x axis: {}", x),
Point { x, y } => println!("Point: ({}, {})", x, y),
}