In Rust, when should a function return Option<T> and when should it return Result<T, E>?
answer
- absence versus failure
- does the caller need a reason
- HashMap::get versus str::parse
- Result is #[must_use]
basics
~20 sReturn Option<T> when having no value is an ordinary outcome that needs no explanation, such as a map lookup; return Result<T, E> when the operation can fail and the caller needs to know why, such as parsing.
solid answer
~40 s`Option<T>` is `Some(T)` or `None`: it says a value may be absent, and the absence carries no reason. `HashMap::get` returns `Option<&V>` because a missing key is a normal answer, not a fault. `Result<T, E>` is `Ok(T)` or `Err(E)`: it says the operation can fail, and `E` describes how, so `str::parse::<u32>` returns `Result<u32, ParseIntError>` and the caller can tell an empty string from an invalid digit. The compiler backs the difference: `Result` is marked `#[must_use]` at the type level, so discarding one triggers the `unused_must_use` warning, while `Option` carries no such mark. If a caller will want to log, report or branch on the reason, return `Result`; if "nothing there" is the whole story, return `Option`.
code
rust · 31 linesuse std::collections::HashMap;
use std::num::ParseIntError;
struct User {
name: String,
age: String,
}
fn find_user(users: &HashMap<u64, User>, id: u64) -> Option<&User> {
users.get(&id) // a missing id is a normal outcome, not a failure
}
fn parse_age(raw: &str) -> Result<u32, ParseIntError> {
raw.trim().parse::<u32>() // malformed text is a failure with a reason
}
fn main() {
let mut users = HashMap::new();
users.insert(7, User { name: "Ada".into(), age: "36".into() });
users.insert(8, User { name: "Bo".into(), age: "thirty".into() });
for id in [7, 8, 9] {
match find_user(&users, id) {
None => println!("{id}: no such user"),
Some(user) => match parse_age(&user.age) {
Ok(age) => println!("{id}: {} is {age}", user.name),
Err(e) => println!("{id}: bad age for {}: {e}", user.name),
},
}
}
}go deeper
Recall the variants of each type and one std function that returns each: HashMap::get returns Option, str::parse returns Result.
Explain the decision rule: absence that needs no reason is Option, failure the caller may act on is Result. Mention the must_use warning on Result.
Show you design signatures for callers: Result<Option<T>, E> when absence is normal and failure is possible, and never a reason-free None for a parse error.
Frame the choice as API contract: the return type documents which outcomes are normal and which are faults, and changing it later breaks every caller.
## Two types, two meanings Safe Rust has no null references, and it does not use exceptions for recoverable failures. Instead, a function says in its **return type** what can go wrong, and the standard library offers two enums for that: - **`Option<T>`** has the variants `Some(T)` and `None`. It models **absence**: there may or may not be a value, and when there is none, there is nothing more to say. - **`Result<T, E>`** has the variants `Ok(T)` and `Err(E)`. It models **failure**: the operation was attempted and may not have succeeded, and the `E` value carries the reason. Both force the caller to deal with the empty case before touching the value: a `u32` cannot be read out of an `Option<u32>` or a `Result<u32, ParseIntError>` without a `match`, an `if let`, a combinator or an explicit extraction. ## The lookup-then-parse scenario Consider a service that keeps users in a `HashMap<u64, User>` and stores each user's age as text that came from a form: 1. **Looking up the user** returns `Option<&User>`. A missing id is a normal answer to the question "is there a user with this id?" and needs no explanation, which is exactly why `HashMap::get` returns `Option<&V>`. 2. **Parsing the age** returns `Result<u32, ParseIntError>`. The text exists, and turning it into a number can fail in distinguishable ways: an empty string, an invalid digit, a value too large for `u32`. `ParseIntError` exposes which one through its `kind()` method. ```rust fn find_user(users: &HashMap<u64, User>, id: u64) -> Option<&User> { users.get(&id) } fn parse_age(raw: &str) -> Result<u32, ParseIntError> { raw.trim().parse::<u32>() } ``` The caller handles the two outcomes differently: "no such user" is a branch of normal control flow, while "bad age for Bo: invalid digit found in string" is a failure worth reporting with its cause. ## How the compiler and std treat them | Aspect | `Option<T>` | `Result<T, E>` | |---|---|---| | Variants | `Some(T)`, `None` | `Ok(T)`, `Err(E)` | | Meaning of the empty case | nothing there | something went wrong, and `E` says what | | Type-level `#[must_use]` | no | yes: "this `Result` may be an `Err` variant, which should be handled" | | Typical std producer | `HashMap::get`, `Vec::first`, `Iterator::next`, `str::find` | `str::parse`, `File::open`, `u8::try_from` | | Converting to the other | `ok_or`, `ok_or_else` | `ok`, `err` | The `#[must_use]` row matters in practice. Writing `"5".parse::<u32>();` as a statement compiles but rustc warns "unused `Result` that must be used" under the `unused_must_use` lint, which is on by default. An ignored `Option` gets no such type-level warning, although individual methods that return one may carry their own `#[must_use]`. ## Choosing in an API Ask what the caller will do with the empty case: - If the caller only needs to know **whether** a value exists, return `Option`. Lookups, searches and "first element" queries belong here. - If the caller may need to **report, log, retry or branch on why**, return `Result` with an error type that carries that information. - If absence is normal **and** the operation can also fail, the honest type is `Result<Option<T>, E>`: for example, a database query that may find no row and may also lose its connection. - Do not return `Result<T, ()>` to mean "maybe": an error type with no information is an `Option` in disguise, and it presents a normal absence as a failure. - Do not return `Option<T>` from an operation whose failure has causes the caller would want; turning a parse error into `None` throws the diagnosis away. ## Common mistakes - Treating `None` as an error message: `None` carries no data, so a function that returns `None` for both "not found" and "malformed" makes the two impossible to tell apart. - Reaching for extraction methods that panic on the empty case as the default way to get the value out; how and when those panic belongs to the material on panics, and the combinators covered elsewhere in this lesson keep the empty case explicit. - Assuming one type is "more correct" than the other: they encode different facts, and many functions legitimately compose both, as the lookup-then-parse code above does. Propagating either type upward with the question-mark operator, and designing custom error enums for `E`, are covered in their own lessons; the choice of type comes first, and it is the one this question is about.
- A Rust repository function may find no row and may also fail to reach the database. What should it return?`Result<Option<Row>, DbError>`. The outer `Result` reports the failure to run the query, with a reason; the inner `Option` reports the ordinary outcome that no row matched. Collapsing both into `Option<Row>` hides outages as "not found", and collapsing both into `Result<Row, DbError>` forces a fake `NotFound` error for a normal answer.
- Why does ignoring a Result produce a compiler warning in Rust while ignoring an Option usually does not?`Result` is declared with `#[must_use = "this `Result` may be an `Err` variant, which should be handled"]`, so any unused `Result` value triggers the default-on `unused_must_use` lint. `Option` has no type-level `#[must_use]`; only individual methods marked `#[must_use]` warn when their `Option` is dropped. Writing `let _ = ...;` silences the warning deliberately.
A library desk answers "we do not hold that book" with a plain no, but a torn request slip gets returned with a note saying which field was unreadable: Option is the plain no, Result is the note.
- Option and Result are interchangeable; pick whichever is shorter to type
- None is a good way to signal that parsing failed
- Result<T, ()> is the idiomatic way to say a value may be missing
- Ignoring a returned Option triggers the same must-use warning as a Result
- A lookup miss in a HashMap should be reported as an Err