Your PHP Status class has three properties: a kind, a nullable $startedAt, and a nullable $exitCode. Nothing in its constructor stops a pending status from carrying an exit code. And when a match misses a case, you find out at run time, from an UnhandledMatchError.
A Rust enum lets each case carry its own data and nothing else, and a match on it doesn't compile until every case is handled.
This lesson covers four things: an enum whose variants carry data, match and the compiler's check that every variant is handled, destructuring, and if let for when you care about one case. For each you get the Rust shape, where it sits in your PHP code, and one trap. It leaves out Option, Result and let-else, which are Lesson 7, and the enum that models task state in a larger program, which is Tutorial 13 of the main series. It assumes Lesson 5: structs, impl blocks and #[derive(Debug)]. If you've used PHP 8.1 enums and match, the keywords will look familiar. You don't have to learn every pattern form today. You can come back to this lesson when a match arm looks strange.
Take a look at Example 1.
Example 1. Complete example (examples/src/bin/b06_enums.rs)
// Lesson b06: enums with data, and match.
#[derive(Debug)]
enum Status {
Pending,
Running { started_at: u32 },
Finished(i32), // the process exit code
}
fn describe(status: &Status) -> String {
match status {
Status::Pending => "waiting to start".to_string(),
Status::Running { started_at } => format!("running since t={started_at}"),
Status::Finished(0) => "finished cleanly".to_string(),
Status::Finished(code) => format!("failed with exit code {code}"),
}
}
fn main() {
let all = [
Status::Pending,
Status::Running { started_at: 120 },
Status::Finished(0),
Status::Finished(2),
];
for status in &all {
println!("{:?} => {}", status, describe(status));
}
// `if let` handles one case and ignores the rest.
if let Status::Running { started_at } = &all[1] {
println!("only the running case: {started_at}");
}
}
Run it from the examples folder:
cargo run --quiet --bin b06_enums
Pending => waiting to start
Running { started_at: 120 } => running since t=120
Finished(0) => finished cleanly
Finished(2) => failed with exit code 2
only the running case: 120A type for each state
A queued job can be pending, running, or finished. Only a running job has a start time, and only a finished job has an exit code. In php/b06_enums.php that takes two pieces: an enum Kind with three cases, and a class Status holding a Kind plus two nullable integers. It needs the class because a PHP enum case cannot hold state.
Rust puts it in one type. Lines 3 to 7 of Example 1 declare an enum, a type that is one of a fixed set of variants, each of which can carry its own data. Pending carries nothing. Running { started_at: u32 } carries a named field. Finished(i32) carries one unnamed value, the exit code. Line 21 builds Status::Running { started_at: 120 }, where Running is the variant and 120 is its payload.
Can a Pending value carry an exit code? No. Pending has no payload.
match, in order
describe, on lines 9 to 16, turns a status into text with match. A match checks a value against patterns in order and runs the arm for the first one that fits. Order matters here. Finished(0) on line 13 comes before Finished(code) on line 14, so a clean exit gets its own message, and exit code 2 falls through to failed with exit code 2.
Line 12 does something new. The arm Status::Running { started_at } takes the variant apart and binds its field to the name started_at, which the format! then uses. That's destructuring: a pattern that breaks a value into its parts and names them. Line 26 prints each status with {:?}, which works because of the #[derive(Debug)] on line 2.
What happens when an arm is missing?
The function label in f06_not_exhaustive.rs had settled on two kinds of status. Its match held an arm for Status::Pending and an arm for Status::Running, and each arm returned one lowercase word. A few lines above it, the enum declared three variants, the last one Finished, carrying nothing. main called label(Status::Finished). The compiler stopped at line 8 and drew a row of dashes under Finished, with the words not covered.
In PHP, a match with no arm for its value throws UnhandledMatchError when that value arrives, and not before. Rust checks when you compile. Take a look at Example 2, the program from that scene.
Example 2. A match with a missing arm (examples/compile-fail/f06_not_exhaustive.rs)
enum Status {
Pending,
Running,
Finished,
}
fn label(status: Status) -> &'static str {
match status {
Status::Pending => "pending",
Status::Running => "running",
}
}
fn main() {
println!("{}", label(Status::Finished));
}
From the examples folder:
rustc --edition=2024 compile-fail/f06_not_exhaustive.rs
error[E0004]: non-exhaustive patterns: `Status::Finished` not covered
--> compile-fail/f06_not_exhaustive.rs:8:11
|
8 | match status {
| ^^^^^^ pattern `Status::Finished` not covered
|
note: `Status` defined here
--> compile-fail/f06_not_exhaustive.rs:1:6
|
1 | enum Status {
| ^^^^^^
...
4 | Finished,
| -------- not covered
= note: the matched value is of type `Status`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
10 ~ Status::Running => "running",
11 ~ Status::Finished => todo!(),
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0004`.The first line is the verdict: E0004, with the missing variant named. The note points back at the enum and marks that variant, and the help section writes the missing arm out for you. Nothing has run. The PHP version of the demo reaches the same kind of failure only by running: it matches 5 against arms for 1 and 2 and prints UnhandledMatchError: Unhandled match case 5.
Now suppose you add a fourth variant, and the match ends with _ => .... Will the compiler ask for a new arm? No. The _ wildcard matches anything, so it already covers the new variant. That keeps describe compiling, whatever variant you add to Status next and however different its data is from the others and whether or not whoever adds it has ever opened the file that holds describe, and the new variant gets whatever text the _ arm returns.
Destructuring beyond enums
Destructuring works on more than enum variants. A second demo, b06_patterns.rs, declares a struct Point with two i32 fields, x and y, on lines 1 to 4. Take a look at Example 3, lines 23 to 29 of that file.
Example 3. Taking a tuple and a struct apart (examples/src/bin/b06_patterns.rs)
let point = (3, 7);
let (x, y) = point;
println!("tuple: x={x} y={y}");
let p = Point { x: 0, y: 7 };
let Point { x, y } = p;
println!("struct: x={x} y={y}");
let (x, y) = point; takes the tuple (3, 7) apart into two names. let Point { x, y } = p; does the same for a struct, using the field names as the variable names.
A match arm can destructure and test at once. Example 4 is where_is, lines 6 to 12 of the same file.
Example 4. Destructuring and testing in one arm (examples/src/bin/b06_patterns.rs)
fn where_is(p: &Point) -> String {
match p {
Point { x: 0, y } => format!("on the y axis at y={y}"),
Point { x, y: 0 } => format!("on the x axis at x={x}"),
Point { x, y } => format!("at ({x}, {y})"),
}
}
The arm Point { x: 0, y } matches only points where x is 0, and names the y. Lines 31 to 33 call where_is on three points. Before you run it, predict: which arm does Point { x: 4, y: 0 } reach? The second, which prints on the x axis at x=4. Run the file, and the first five lines of its output are these:
cargo run --quiet --bin b06_patterns
tuple: x=3 y=7
struct: x=0 y=7
on the y axis at y=7
on the x axis at x=4
at (2, 5)Handling one case with if let
Sometimes you care about one variant and nothing else. Lines 29 to 32 of Example 1 handle that: if let Status::Running { started_at } = &all[1] runs its block only when the value is Running, and every other variant skips it.¹ That block gives the last line of output, only the running case: 120. if let handles one pattern and gives up the exhaustiveness check. So if you add a variant that needs its own message, will an if let warn you? No. Use a full match for that.
What does the enum promise?
So the program runs, and a pending job with an exit code can't be built, because Pending has nowhere to put one. That's the promise, and it's about the shape of the data. The enum fixes which data goes with which variant. It says nothing about which variant may follow which: nothing in Status stops code from replacing a Finished(2) with Pending. Should a finished job ever start again in your application? If it can, is that the same job or a new one? Where would you write that rule down?
Testing
The main claim is that a match on an enum must handle every variant before the program compiles. Example 2 is the failing case, and the compiler names the missing variant, Status::Finished. Example 1 is the passing case: the four arms in describe cover all three variants, with two of them for Finished, and the run prints a line for each of the four statuses in all. The order claim shows in the output as well. Finished(0) => finished cleanly and Finished(2) => failed with exit code 2 come from different arms, because Finished(0) on line 13 is tried first.
Then find a PHP class of yours with two nullable properties that are only ever set together, and sketch it as an enum with one variant per case. You can keep the nullable version while you learn. The enum is there when the missing case becomes a bug.
TL;DR
An enum is a type that is one of a fixed set of variants, and each variant carries exactly its own data, so a pending job with an exit code can't be built. match tries its arms in order and must cover every variant; a missing one stops the compile with E0004, where PHP's match throws UnhandledMatchError only when the value arrives. A _ arm covers anything, including variants added later. Destructuring takes an enum variant, a tuple or a struct apart into named pieces, and a match arm can destructure and test at once. if let handles one pattern and gives up the exhaustiveness check. Next is Lesson 7, where Option and Result turn out to be enums like these.
¹ all, on line 19, is an array, the fixed-length kind from Lesson 4, and &all[1] borrows its second element, the Running status.