MARY.WIN

RUSTY — LARAVEL TO RUST — 06

Option
instead of null

Make a missing selection explicit without inventing a fake action.
Tutorial 6 of 16 in From Laravel to Rust. Before you start: Structs and match expressions introduced here.

What should the palette display when ID 99 is absent? In examples/src/bin/ep06.rs, the catalog contains ID 7. find() returns an optional reference, and label() turns ordinary absence into the prompt Choose an action.

A PHP nullable return type can declare that a lookup returns an Action or null. The Rust lookup declares Option<&Action>. Some contains a borrowed action when the ID matches. None records that no action matched.

Read both branches of label() before running the example. Predict the label for ID 7, then predict the label for ID 99.

This lesson covers Option<T>: a return type that says a value may be absent, and a match that has to say what absence means. We'll look up an action by ID and label the result. It leaves out failure, which is Result and Tutorial 7, beyond one nested example. It assumes structs and borrowing; match is introduced here.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep06.rs)

#[derive(Debug)]
struct Action { id: u32, title: String }

fn find(actions: &[Action], id: u32) -> Option<&Action> {
    actions.iter().find(|action| action.id == id)
}

fn label(action: Option<&Action>) -> &str {
    match action {
        Some(action) => &action.title,
        None => "Choose an action",
    }
}

fn main() {
    let actions = vec![Action { id: 7, title: "Run tests".into() }];
    assert_eq!(label(find(&actions, 7)), "Run tests");
    assert_eq!(label(find(&actions, 99)), "Choose an action");
    println!("{}", label(find(&actions, 99)));
}

Run it from the examples/ directory and compare the output with your two predictions.

Expected output:

TERMINAL
cargo run --quiet --bin ep06
Choose an action

The terminal shows one line because the final print uses ID 99. Both of your predictions are checked above it: the first assertion checks that ID 7 produces Run tests, and the second checks that ID 99 produces Choose an action.

The successful search that found nothing

label had been written on the understanding that the catalog would not always have the answer. Of its two arms, one returned a title it borrowed, and the other returned a literal, sixteen characters long, that it kept for the purpose. The catalog in main held one action, ID 7, built on a single line. On its last line main asked find for ID 99. find made one comparison, 7 against 99, and returned None. label took the second arm. The terminal printed Choose an action.

Sometimes a search runs correctly and finds nothing, and the code that receives the result has to say what that means. Thankfully, the return type can carry the possibility. Take another look at Example 1.

There are two new pieces. find(actions: &[Action], id: u32) iterates over the borrowed catalog, and its predicate compares action.id with id. A match produces Some(&Action); no match produces None. label matches on that result: for Some(action) it returns &action.title, and its None branch returns the literal Choose an action. Some(action) names the case and binds the contained value; None forces a decision about what ordinary absence means at this boundary.

No fabricated Action is needed to represent the missing result. Trace the two lookups in the assertions and line each one up with its branch: ID 7 with Some(action) and Run tests, ID 99 with None and Choose an action.

What is the default for?

You can also write this with Option's convenience methods: map an existing action to its title and supply a fallback for None. That is concise. I'd name the fallback before choosing the method.

“Choose an action” is a display default, whereas a fallback that ran the first action in the catalog would be a behavioral default, and the two are, as far as Option's method list is concerned and as far as any tool that fills in missing values until compilation succeeds is concerned, the same one-line call with a different argument, though only one of them starts something the user did not ask for.

The same goes for an empty string. Replace a missing value with "" and the program can no longer tell no selection from an invalid selection from a selected action whose title is empty.

Absence and ownership are separate

Suppose we hold an Option<String>. A consuming method can move the String out of the option. To inspect it, as_ref or as_deref produces a borrowed option instead. Example 1 avoids copying by returning Option<&Action>, which stays tied to the catalog. For a snapshot that outlasts catalog edits, return an owned result.

Missing is not unavailable

Now imagine loading actions from storage. The load might fail, or succeed and find no action. A return shape for that is Result<Option<Action>, LoadError>: did loading succeed, and if so, was an action present? That is three outcomes the application has, and the nesting says so. Flattening a storage failure into None would make an unavailable database look like an empty catalog.¹

So the missing lookup renders a prompt and nothing breaks. Now pick one place in your application that receives a nullable. If the value is missing, is that normal there, or is it a NotFound? Who decides: the lookup, or its caller? And does anything downstream treat “missing” as permission to pick something else?

Testing

In Example 1, replace the seeded catalog with an empty vector. Predict label(find(&actions, 7)) and label(find(&actions, 99)), and write both predictions down before you run the modified example.

Both calls return Choose an action, because both lookups produce None. The first assertion still expects Run tests, so update it to match the empty fixture.

Then, as a negative example, replace the match in label with a call to unwrap. The missing result now panics. Restore the explicit None behavior afterward.

You can also try a new example with an optional timeout. Decide separately what None and Some(0) mean before you choose a fallback method.

Last, reconstruct both branches of label from memory, then compare them with the two assertions in main.

TL;DR

Option<T> is Some(value) or None, and match makes the caller handle both. Option<&Action> preserves the lookup result without inventing an entry, and label assigns a display policy to None. A fallback is a product decision; a display default and a behavioral default are different sizes of decision. Absence and ownership are separate dimensions, and a storage failure needs a separate result: Result<Option<T>, E> keeps “not found” apart from “could not look”. Next: an operation that was attempted and could not complete.

¹ A missing lookup can be normal in one context and an error in another. During search, zero matches is ordinary. For an operation addressed to a required existing task, the application may convert absence into a NotFound error. Option carries the fact; the caller assigns the policy.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust Book, Defining an Enum and The Option Enum; standard-library Option methods; PHP Manual, nullable type declarations.

NOT CHECKED — 4
  • That with an empty catalog both lookups return Choose an action, once the first assertion is updated. This exercise is not among the checks run for this edition.
  • That replacing the match in label with unwrap panics on the missing result.
  • The PHP nullable-return comparison. No PHP was run for this page.
  • The reference links were not opened for this page.