Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Patterns can match literal values directly. Both Rust and PHP support this.

Rust

fn main() {
    let number = 1;
    match number {
        1 => println!("One"),
        2 => println!("Two"),
        3 => println!("Three"),
        _ => println!("Other"),
    }
}

PHP

<?php
$number = 1;
echo match ($number) {
    1 => "One",
    2 => "Two",
    3 => "Three",
    default => "Other",
} . "\n";

Comparison

  • Rust: Literals (integers, chars, strings) matched by value; _ is the catch-all.
  • PHP: match uses ===; default is the catch-all.
  • Rust: No fall-through; each arm is independent.
  • PHP: No fall-through; each case is separate.

References

What's next

Next: Matching with variables.

From PHP to Rust — Rust Syntax and Functions