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

Matching on enum variants lets you extract their data. Rust supports full destructuring; PHP can destructure arrays, but enum-like class hierarchies are usually handled with instanceof and property access.

Rust

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let messages = [
        Message::Quit,
        Message::Move { x: 10, y: 20 },
        Message::Write(String::from("Hello")),
        Message::ChangeColor(255, 120, 0),
    ];
    for msg in messages {
        match msg {
            Message::Quit => println!("Quit"),
            Message::Move { x, y } => println!("Move to ({}, {})", x, y),
            Message::Write(text) => println!("Write: {}", text),
            Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
        }
    }
}

PHP

<?php
// With classes
$msg = new Move(10, 20);
match (true) {
    $msg instanceof Quit => print("Quit\n"),
    $msg instanceof Move => print("Move to ({$msg->x}, {$msg->y})\n"),
    $msg instanceof WriteMessage => print("Write: {$msg->text}\n"),
    default => print("Other\n"),
};

// PHP array destructuring example
[$x, $y] = [10, 20];
print("Array values: {$x}, {$y}\n");

Comparison

  • Rust: Destructuring in the pattern; variant and data extracted in one step.
  • PHP: Array destructuring exists ([$a, $b] = ...), but enum-like class hierarchies typically use instanceof plus property access.
  • Rust: Compiler checks exhaustiveness.
  • PHP: Use default or ensure all cases are covered.

References

What's next

Next: Enum methods.

From PHP to Rust — Rust Syntax and Functions