Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Match guards are if conditions after a pattern. The arm runs only when the pattern matches and the guard is true. PHP match has no guards; use if/else or conditions inside the arm.
Rust
struct Point { x: i32, y: i32 }
fn main() {
let point = Point { x: 0, y: 10 };
match point {
Point { x: 0, y } if y < 5 => println!("On y-axis, close to origin"),
Point { x: 0, y } => println!("On y-axis at {}", y),
Point { x, y: 0 } if x > 5 => println!("On x-axis, far from origin"),
Point { x, y } => println!("Point at ({}, {})", x, y),
}
}
PHP
<?php
$point = ['x' => 0, 'y' => 10];
if ($point['x'] === 0 && $point['y'] < 5) {
echo "On y-axis, close to origin\n";
} elseif ($point['x'] === 0) {
echo "On y-axis at {$point['y']}\n";
} elseif ($point['y'] === 0 && $point['x'] > 5) {
echo "On x-axis, far from origin\n";
} else {
echo "Point at ({$point['x']}, {$point['y']})\n";
}
Comparison
- Rust: Guard is
if conditionafter the pattern; combines pattern and extra checks. - PHP: Logic expressed in
if/elseifchains. - Rust: Guards can refer to bindings from the pattern.
- PHP: No pattern syntax; use plain conditionals.
References
What's next
Next: Matching ranges.
From PHP to Rust — Rust Syntax and Functions