Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
match in Rust is an exhaustive pattern matcher. It can match literals, variables, ranges, enums, structs, and more. PHP 8’s match is an expression-based switch that compares by identity.
Rust
fn main() {
let number = 1;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Other"),
}
}
PHP
<?php
$number = 1;
$result = match ($number) {
1 => "One",
2 => "Two",
3 => "Three",
default => "Other",
};
echo "$result\n";
Comparison
- Rust: Patterns can destructure and bind; must be exhaustive (or use
_). - PHP:
matchcompares by===;defaulthandles remaining cases. - Rust: Arms can be blocks;
matchis an expression. - PHP: Each arm is an expression; no fall-through.
References
What's next
Next: Matching literals.
From PHP to Rust — Rust Syntax and Functions