Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Patterns can bind matched values to variables. In Rust, use variable names in patterns; match guards add extra conditions. PHP match returns values but does not destructure or bind like Rust.
Rust
fn main() {
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("Equal"),
(x, y) if x + y == 0 => println!("Opposites"),
(x, y) => println!("Different: ({}, {})", x, y),
}
}
PHP
<?php
$pair = [2, -2];
[$x, $y] = $pair;
if ($x === $y) {
echo "Equal\n";
} elseif ($x + $y === 0) {
echo "Opposites\n";
} else {
echo "Different: ($x, $y)\n";
}
Comparison
- Rust: Patterns bind variables;
ifguards add conditions; destructuring in the pattern. - PHP: Destructuring via
[$a, $b] = $arr; conditions inif/elseif. - Rust: Variable binding is part of the pattern; guards use
ifafter the pattern. - PHP: No pattern binding in
match; use separate destructuring and conditionals.
References
What's next
Next: Combining patterns.
From PHP to Rust — Rust Syntax and Functions