4. Match
by anonymous · 2026-06-01 07:32:11 · 21 views
Match vs Switch: Basic Expression
Switch(C)
int num = 2;
switch(num) {
case 1:
printf("One\n");
break;
case 2:
/* fall through */
case 3:
printf("Two or Three\n");
break;
default:
printf("Something else\n");
}
Match(Rust)
let number = 2;
match number {
1 => println!("One"),
2 | 3 => println!("Two or Three"), // OR operand
_ => println!("Something else"),
}
Easy? Yes. Short? Yes. No dirty fall through? Yes.
This is perfectly fine.
Match vs If: Dirty Expressions-Structs
C
typedef struct {
int x;
int y;
} Point;
void process_point(Point p) {
// 1. Manually check x, then extract y
if (p.x == 0) {
int y = p.y;
printf("On the Y axis: y = %d\n", y);
}
// 2. Manually check y, then extract x
else if (p.y == 0) {
int x = p.x;
printf("On the X axis: x = %d\n", x);
}
// 3. Fallback
else {
int x = p.x;
int y = p.y;
printf("Coordinates: (%d, %d)\n", x, y);
}
}
Rust
struct Point { x: i32, y: i32 }
fn process_point(point: Point) {
match point {
// Checks if x == 0, and extracts y simultaneously
Point { x: 0, y } => println!("On the Y axis: y = {}", y),
// Checks if y == 0, and extracts x simultaneously
Point { x, y: 0 } => println!("On the X axis: x = {}", x),
// Fallback: extracts both x and y
Point { x, y } => println!("Coordinates: ({}, {})", x, y),
}
}
Easy? Yes. Clean? Yes. Safe? Yes.
Match vs If: Match Guards
typedef struct { int x; int y; } Pair;
void process_pair(Pair p) {
// C doesn't support complex matching in switch, so we use if-else chains
int x = p.x;
int y = p.y;
if (x + y == 0) {
printf("Canceled out! (%d, %d)\n", x, y);
} else if (x == y) {
printf("Identical values!\n");
} else {
printf("Ordinary data: %d, %d\n", x, y);
}
}
Rust
fn process_pair(pair: (i32, i32)) {
match pair {
// Extracts x and y, but 'only' enters this arm if x + y == 0
(x, y) if x + y == 0 => println!("Canceled out! ({}, {})", x, y),
// 'only' enters this arm if x == y
(x, y) if x == y => println!("Identical values!"),
// Fallback
(x, y) => println!("Ordinary data: {}, {}", x, y),
}
}
Easy? Nope. Safe? Yes.
...C version is also dirty? Yes.
This is a good trade-off.
Impressions
Smart? Yes.
Simple? Yes.
Easy-to-learn? ...Soso.