MARY.WIN

RUSTY — BEGINNER — B07

Option and Result: null and exceptions, first
look

Rust writes "this might be missing" and "this might fail" into the return type, and the caller has to look inside before using the value.
Lesson 7 of 9 in Rust beginner track. Before you start: Lessons 4 and 6.

You search a PHP array for a task called Deploy. It isn't there. positionOf() returns null, the next line adds one to it, and the script prints next index = 1. Nothing complained.

Rust has no null in ordinary types. A function that might not find something says so in its return type, a function that might fail says that too, and adding a number to a value that might be missing doesn't compile.

Here are both kinds in one file. position_of() returns an Option. parse_minutes() and total_minutes() return a Result.

This lesson covers the two standard enums Rust uses where PHP uses null and exceptions: Option<T> for a value that might be missing, and Result<T, E> for an operation that might fail. You'll open them with match, if let, let-else, unwrap_or and the ? operator, and see what unwrap does when you're wrong. It assumes Lesson 4, where reading past the end of a Vec panicked, and Lesson 6, where you matched on enums. The main series covers both types at length.

Take a look at Example 1.

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

// Lesson b07: Option for "might be missing", Result for "might fail".
fn position_of(tasks: &[&str], name: &str) -> Option<usize> {
    tasks.iter().position(|t| *t == name)
}

fn parse_minutes(input: &str) -> Result<u32, String> {
    input
        .trim()
        .parse::<u32>()
        .map_err(|e| format!("'{input}' is not a minute count: {e}"))
}

fn total_minutes(inputs: &[&str]) -> Result<u32, String> {
    let mut total = 0;
    for input in inputs {
        total += parse_minutes(input)?; // `?` returns early with the error
    }
    Ok(total)
}

fn main() {
    let tasks = ["Run tests", "Clear cache"];

    // Option
    println!("{:?}", position_of(&tasks, "Clear cache"));
    println!("{:?}", position_of(&tasks, "Deploy"));
    match position_of(&tasks, "Deploy") {
        Some(i) => println!("found at {i}"),
        None => println!("not found"),
    }
    println!("with a default: {}", position_of(&tasks, "Deploy").unwrap_or(0));
    if let Some(i) = position_of(&tasks, "Run tests") {
        println!("if let found {i}");
    }

    // Result
    println!("{:?}", parse_minutes(" 45 "));
    println!("{:?}", parse_minutes("soon"));
    println!("{:?}", total_minutes(&["10", "20", "15"]));
    println!("{:?}", total_minutes(&["10", "later", "15"]));
}

From the examples folder, run it with Cargo:

TERMINAL
cargo run --quiet --bin b07_option_result
Some(1)
None
not found
with a default: 0
if let found 0
Ok(45)
Err("'soon' is not a minute count: invalid digit found in string")
Ok(45)
Err("'later' is not a minute count: invalid digit found in string")

What does Option say that ?int doesn't?

PHP's positionOf() is declared ?int, and the declaration is honest. Nothing makes the caller read it. Rust's version can't be used that way; take a look at position_of() at the top of Example 1.

Its return type, Option<usize>, is the standard enum for a value that may be absent. It has two variants: Some(T) holds a value, and None holds nothing. Ordinary Rust types have no null, so absence always shows up in the type. Option<usize> sits where ?int sits, except that you must handle the missing case. The first two lines of output are the two cases: Some(1) for Clear cache, None for Deploy.

Three ways to look inside

How do you get the number out? You decide what happens on None, and there are three ways to write that decision down.

The match in Example 1 writes both arms: Some(i) gets the index, and None prints not found. The if let Some(i) runs its block only on Some, for when None means skip it.

The third, let-else, binds the value for the rest of the function or leaves it. Take a look at Example 2.

Example 2. Bind it or leave (examples/src/bin/b07_let_else.rs)

fn position_of(tasks: &[&str], name: &str) -> Option<usize> {
    tasks.iter().position(|t| *t == name)
}

fn describe(tasks: &[&str], name: &str) -> String {
    let Some(i) = position_of(tasks, name) else {
        return format!("{name} is not in the list");
    };
    format!("{name} is task number {}", i + 1)
}

fn main() {
    let tasks = ["Run tests", "Clear cache"];
    println!("{}", describe(&tasks, "Clear cache"));
    println!("{}", describe(&tasks, "Deploy"));
}

Run it with cargo run --quiet --bin b07_let_else:

OUTPUT
Clear cache is task number 2
Deploy is not in the list

There's one new statement here. let Some(i) = position_of(tasks, name) else { ... }; binds i when the search finds something. When it doesn't, the else block runs, and it must leave the function; this one returns Deploy is not in the list. Every line after the statement uses i directly.

What if the else block only prints a message and carries on? Example 3 tries it.

Example 3. An else that keeps going (examples/compile-fail/f07_let_else_no_return.rs)

fn describe(tasks: &[&str], name: &str) -> String {
    let Some(i) = tasks.iter().position(|t| *t == name) else {
        println!("{name} is missing");
    };
    format!("{name} is task number {}", i + 1)
}

fn main() {
    println!("{}", describe(&["Run tests"], "Deploy"));
}

The compiler stops with this:

OUTPUT
error[E0308]: `else` clause of `let...else` does not diverge
 --> compile-fail/f07_let_else_no_return.rs:2:62
  |
2 |       let Some(i) = tasks.iter().position(|t| *t == name) else {
  |  ______________________________________________________________^
3 | |         println!("{name} is missing");
4 | |     };
  | |_____^ expected `!`, found `()`
  |
  = note:   expected type `!`
          found unit type `()`
  = help: try adding a diverging expression, such as `return` or `panic!(..)`
  = help: ...or use `match` instead of `let...else`

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

E0308: the else clause does not diverge. It has to return or panic; otherwise i would have no value on the next line. The second help: line offers match as the other way out.

Is zero a good default?

The call unwrap_or(0) held that a missing task was worth zero. It sat at the end of a println! whose text began with a default:, and when the search for Deploy came back None, it printed 0 as instructed. On the next line of output, if let found Run tests and printed that task's index. It was 0 too.

Sometimes you'd rather have a stand-in value than a branch, and in PHP you'd reach for ??. unwrap_or does that job: it returns the inside of a Some, or the default you pass. Choosing the default is a design decision. In Example 1, 0 is also where Run tests sits, so the missing task now looks like the first one.

Can you skip the decision and do arithmetic on the Option directly? Example 4 holds Some(30) and adds 15.

Example 4. Arithmetic on an Option (examples/compile-fail/f07_option_math.rs)

fn main() {
    let maybe_minutes: Option<u32> = Some(30);
    let total: u32 = maybe_minutes + 15;
    println!("{total}");
}
OUTPUT
error[E0369]: cannot add `{integer}` to `Option<u32>`
 --> compile-fail/f07_option_math.rs:3:36
  |
3 |     let total: u32 = maybe_minutes + 15;
  |                      ------------- ^ -- {integer}
  |                      |
  |                      Option<u32>
  |
note: `Option<u32>` does not implement `Add<{integer}>`
 --> /rustc/0ef1bc386059596dada8fb65b50425aab2ea637a/library/core/src/option.rs:598:0
  |
  = note: `Option<u32>` is defined in another crate

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0369`.

No. E0369: you can't add an integer to Option<u32>. The value is a number or nothing, and the addition has to know which.¹

A deliberate crash

In Lesson 4, reading past the end of a Vec panicked. A panic is Rust's response to an unrecoverable error.² Sometimes you're sure a value is there, and if you're wrong, you want that same loud stop. That's unwrap: it returns the inside of a Some or an Ok, and it panics on None or Err.

Example 5. Unwrap on a missing value (examples/src/bin/b07_unwrap_panic.rs)

// Lesson b07: `unwrap` turns a missing value into a panic.
fn main() {
    let tasks = ["Run tests"];
    let found: Option<usize> = tasks.iter().position(|t| *t == "Deploy");
    println!("looked for Deploy");
    println!("{}", found.unwrap());
}

Run it with cargo run --quiet --bin b07_unwrap_panic. It prints one line:

OUTPUT
looked for Deploy

and then the panic message on standard error, which begins:

OUTPUT
thread 'main' (54287855) panicked at src/bin/b07_unwrap_panic.rs:6:26:
called `Option::unwrap()` on a `None` value

Does unwrap panic on Some(0)? No. It returns 0. Zero is a value.

The Rust Book says panicking fits examples, prototype code, tests, and cases where you know more than the compiler. An unwrap right after a search will also get past the type checker, and it is, depending on whether the list was built two lines earlier from literals you can see or arrived from a form or a file, and on whether a stopped program at that line means a bug report or a stopped service, either a fair statement of what you know or a guess, and the line reads the same either way. Elsewhere in this course, a missing value is a case to handle.

An operation that might fail

In the PHP file, parseMinutes('soon') throws, and a catch prints caught: 'soon' is not a minute count. The return type says int and nothing about throwing. You want a type that says: a number, or the reason there isn't one.

That type is Result<T, E>, the standard enum for an operation that can fail. Ok(T) holds the success value, and Err(E) holds the error. Nothing is thrown; the error comes back the way a value would. In Example 1, parse_minutes() returns Result<u32, String>. It trims the input, parses a u32, and map_err turns the parse error into a String. " 45 " gives Ok(45), and "soon" gives the Err on the seventh line of output. A Rust program can still panic; Result is for the failures you expect the caller to handle.

Does None mean the parse failed? No. Here None means not there, and Err means not a number. Read the signature first.

Handing a failure up

total_minutes() parses a whole list, and when one input fails, you want to stop and hand the error to the caller. Rust has one character for that. Put ? after a Result, and you get the Ok value, or the Err is returned from the current function right away. The function must return a compatible Result or Option. It's an exception propagating, except that you can see it at each call. 10, 20, 15 gives Ok(45). 10, later, 15 returns the Err at later, and the 15 is never parsed.

Does ? undo the additions it already made? No. It returns. A database write before the ? would stay written.

Who decides what missing means?

So all nine lines of Example 1 came out, and the lesson could stop here. But go back to the PHP file. Its null meant not found, its ?? turned not found into 0, and its catch printed a bad minute count and moved on. Each was a decision about what missing or failed means, made at the call by whoever wrote that line. Rust moves the first half of the decision into the signature. The second half is still yours. When your own code can't find a task, is that a None, an Err, or a bug that should stop the program? Who decided? Where is it written down?

Testing

Cover the output of Example 1 and predict all nine lines before you run it. Watch the fourth and fifth: both are 0, for different reasons.

Before compiling Examples 3 and 4, write down the error code you expect. Then compile each one from the examples folder, for example with rustc --edition=2024 compile-fail/f07_option_math.rs, and compare.

Then, away from this page, take a PHP function of yours that returns ?int or throws, and say which Rust type it would return. You don't have to get it right every time. You can change a return type later, and the compiler points at the callers that no longer fit.

TL;DR

Option<T> is Some(T) or None, for a value that might be missing, and Result<T, E> is Ok(T) or Err(E), for an operation that might fail. You open them with match, if let, let-else, whose else must leave the function, or unwrap_or, whose default is a design decision. You can't do arithmetic on an Option until you've opened it. unwrap returns the value or panics, so it belongs where a crash is the right answer. ? hands an Err up to the caller and undoes nothing. Next: how Rust splits a program into modules and files.

¹ The second note: in that message points into the standard library's own source, at a path that begins /rustc/, because that is where Option is defined. For this error, the labels under line 3 carry the useful part: Option<u32> on the left of the +.

² By default a panic unwinds the stack. A build can set panic = 'abort' in a Cargo profile instead, so treat unwinding as the default, not as something every Rust binary does.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 1
  • Rust Book [S20] ch. 6.1 (Option), 6.3 "Staying on the Happy Path with let...else", 9.1 "Unrecoverable Errors with panic!", 9.2 "Recoverable Errors with Result", 9.3 "To panic! or Not to panic!"; std docs [S24] for Option, Result; Rust Reference [S25] "let statements"; Error Codes Index [S63] E0308, E0369; PHP Manual [S27] "Comparison Operators" (null coalescing) and "Exception". Books: TRPL 3rd ed. [S17] ch. 9 "Unrecoverable Errors with the panic! Macro" 19.5, ch. 9 "Propagating Errors > Where to Use the ? Operator" 19.6, ch. 8 "Hash Maps > Accessing Values" 18.8; Programming Rust 3rd ed. [S18] ch. 7 "Panic"; Learn Rust in a Month of Lunches [S19] 5.2.1, 8.3.1.

Rust Book: Defining an enum · Rust Book: if let and let...else · Rust Book: Unrecoverable errors with panic! · Rust Book: Recoverable errors with Result · Rust Book: To panic! or not to panic! · std: Option · std: Result · Rust Reference: Statements · Error index: E0369 · PHP Manual: null coalescing operator · PHP Manual: Exception

NOT CHECKED — 7
  • The E0369 error for adding an integer to an Option comes from the example compiled for this lesson; the Rust Book shows E0369 only for a different kind of operand.
  • A panic unwinds the stack by default, but a build can set panic = 'abort', and then it doesn't. The lesson states the default only.
  • That unwrap on Some(0) returns 0 comes from the standard library documentation; no example in this lesson runs it.
  • That ? leaves earlier work in place, such as a database write, follows from the Rust Book's description of early return; no example in this lesson writes anything.
  • That changing a return type makes the compiler point at the callers that no longer fit is stated from general use; no example in this lesson demonstrates it.
  • The panic message was recorded once; the number after thread 'main' is from that run and was not compared with other runs.
  • Compiler messages and program output were recorded with rustc 1.100.0, and the PHP output with PHP 8.5.8. Other versions can word or lay out the same messages differently.