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

Option<T> represents an optional value: Some(T) or None. Matching handles both cases exhaustively. PHP uses null for absence; nullable types and ? provide similar semantics.

Rust

fn show_age(name: &str, age: Option<u8>) {
    match age {
        Some(value) => println!("{} is {} years old", name, value),
        None => println!("{} has no age set", name),
    }
}

fn main() {
    let alice_age = Some(30);
    let bob_age: Option<u8> = None;

    show_age("Alice", alice_age);
    show_age("Bob", bob_age);
}

PHP

<?php
$some_number = 5;
$absent_number = null;

echo $some_number !== null ? "The number is: $some_number" : "No number";
echo "\n";
echo $absent_number !== null ? "The number is: $absent_number" : "No number";
echo "\n";

// With match
echo match (true) {
    $some_number !== null => "The number is: $some_number",
    default => "No number",
} . "\n";

Comparison

  • Rust: Option forces handling None; no null pointer dereference.
  • PHP: null represents absence; use ?T and null checks.
  • Rust: match ensures both variants are handled.
  • PHP: Null coalescing ?? and null-safe ?-> simplify null handling.

References

What's next

Next: Smart user input classifier exercise.

From PHP to Rust — Rust Syntax and Functions