Option and Result
Two enums sit at the heart of almost every Rust program you will ever write: Option<T> and Result<T, E>. They replace null pointers, and the unchecked exceptions a program is expected to recover from, with types the compiler enforces. Once you internalise both, you gain a superpower: the compiler tells you exactly where something might be absent or might fail, and refuses to compile until you have handled it.
Option — Values That May Not Exist
Option<T> models the idea of "a value that is either present or not". The standard library defines it as:
enum Option<T> {
None, // nothing is here
Some(T), // a value is present
}
Returning None is Rust's safe alternative to returning null. Because the type system tracks whether a value is wrapped in Option, you can never accidentally use a "null" value without checking it first.
Basic Option Usage
fn find_first_even(numbers: &[i32]) -> Option<i32> {
for &n in numbers {
if n % 2 == 0 {
return Some(n);
}
}
None
}
fn main() {
let odds = vec![1, 3, 5, 7];
let mixed = vec![1, 3, 4, 6];
match find_first_even(&odds) {
Some(n) => println!("Found even number: {}", n),
None => println!("No even numbers in the list"),
}
match find_first_even(&mixed) {
Some(n) => println!("Found even number: {}", n),
None => println!("No even numbers in the list"),
}
}
match is the most explicit way to handle an Option, but Rust provides several concise combinators for common patterns.
Option Combinators
Combinators let you transform and chain Option values without nested match blocks:
fn username_initials(name: &str) -> Option<String> {
// Split on whitespace, collect first letters, return None if no words
let initials: String = name
.split_whitespace()
.filter_map(|word| word.chars().next())
.map(|c| c.to_ascii_uppercase())
.collect();
if initials.is_empty() { None } else { Some(initials) }
}
fn main() {
let names = vec!["alice bob", "", "carol dan eve"];
for name in &names {
// map: transform the Some value, leaving None untouched
let display = username_initials(name)
.map(|i| format!("Initials: {}", i))
.unwrap_or_else(|| String::from("(no name)"));
println!("{:?} => {}", name, display);
}
// unwrap_or gives a default without panicking
let score: Option<u32> = None;
println!("Score: {}", score.unwrap_or(0));
// and_then chains operations that each return an Option
let raw: Option<&str> = Some(" 42 ");
let parsed: Option<u32> = raw
.map(str::trim)
.and_then(|s| s.parse().ok());
println!("Parsed: {:?}", parsed);
}
Key combinators to know:
| Combinator | What it does |
|---|---|
map(f) | Transform Some(x) to Some(f(x)); pass None through |
and_then(f) | Chain: call f(x) which itself returns an Option |
unwrap_or(default) | Extract the value or use the fallback |
unwrap_or_else(f) | Like unwrap_or but the fallback is lazily computed |
filter(pred) | Keep Some(x) only if pred(x) is true |
The first two rows of that table are the ones people mix up, and the table alone will not fix it — the difference only becomes obvious when you look at the type that comes back. In the program below, chains A and B call the identical closure; the only difference is map versus and_then. Predict all four printed lines before running.
Predict
first_word returns an Option. Chain A feeds it to map, chain B feeds the same closure to and_then, and chain C uses map with a closure that returns a plain value. What exactly does each line print?
fn first_word(line: &str) -> Option<&str> {
line.split_whitespace().next()
}
fn main() {
let line = Some("42 apples");
// Chain A: the closure returns an Option, and we used map.
let a = line.map(|l| first_word(l));
// Chain B: the same closure, but with and_then.
let b = line.and_then(|l| first_word(l));
// Chain C: map with a closure that returns a plain value, not an Option.
let c = line.map(|l| l.len());
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("c = {:?}", c);
println!("b unwrapped or fallback = {}", b.unwrap_or("(none)"));
}a is Some(Some("42")), b is Some("42"), c is Some(9), and the last line prints 42. map takes whatever the closure returned and wraps it in a fresh Some — so a closure that already returns an Option gives you an Option inside an Option. and_then expects the closure to be fallible and uses its Option directly. Chain C is what map is for: l.len() is a plain usize, so wrapping it is exactly right. The short version: plain value out of the closure → map; another Option out of the closure → and_then. The same rule holds for Result, where and_then plays the same flattening role.
Result — Operations That Can Fail
Result<T, E> models a computation that either succeeds with a value of type T or fails with an error of type E:
enum Result<T, E> {
Ok(T), // success
Err(E), // failure, with an error value
}
Any function that can fail should return Result instead of panicking. Callers are then forced by the compiler to decide what to do with errors.
Defining and Returning Results
#[derive(Debug)]
enum ParseError {
Empty,
InvalidFormat(String),
OutOfRange(i32),
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseError::Empty => write!(f, "input was empty"),
ParseError::InvalidFormat(s) => write!(f, "invalid format: {}", s),
ParseError::OutOfRange(n) => write!(f, "value {} is out of range (1–100)", n),
}
}
}
fn parse_score(input: &str) -> Result<i32, ParseError> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Err(ParseError::Empty);
}
let n: i32 = trimmed
.parse()
.map_err(|_| ParseError::InvalidFormat(trimmed.to_string()))?;
if !(1..=100).contains(&n) {
return Err(ParseError::OutOfRange(n));
}
Ok(n)
}
fn main() {
let inputs = ["42", "", "abc", "200", " 77 "];
for input in &inputs {
match parse_score(input) {
Ok(score) => println!("{:?} => score {}", input, score),
Err(e) => println!("{:?} => error: {}", input, e),
}
}
}
Notice the ? at the end of the .parse() call. If the parse fails, ? returns the Err early, after running map_err to convert the error type. This is the idiomatic Rust way to propagate errors.
The ? Operator
The ? operator is shorthand for "if this is an Err (or None), return it immediately; otherwise give me the inner value." It dramatically reduces boilerplate in functions that call multiple fallible operations in sequence:
use std::num::ParseIntError;
fn add_str_numbers(a: &str, b: &str) -> Result<i32, ParseIntError> {
// ? propagates the error and returns early if parsing fails
let x: i32 = a.trim().parse()?;
let y: i32 = b.trim().parse()?;
Ok(x + y)
}
fn main() {
println!("{:?}", add_str_numbers("10", "32")); // Ok(42)
println!("{:?}", add_str_numbers("10", "oops")); // Err(...)
println!("{:?}", add_str_numbers(" 5 ", " 5 ")); // Ok(10)
}
Read that sentence about ? carefully, because it hides a constraint that trips up almost everyone: ? can only return early from the function it is written in, so the function's return type has to be able to hold what ? is bailing out with. A ? on an Option inside a function returning Result does not compile — there is no error value for it to produce. A ? on a Result<_, E1> inside a function returning Result<_, E2> only compiles if E2 can be built from E1, which is why add_str_numbers above declares its error type as ParseIntError, precisely the error .parse() produces.
? works identically for Option inside functions that return Option.
Recall
Without scrolling up: in Pattern Matching you learned that a match must be exhaustive — the compiler rejects it unless every possible value of the matched type is covered. Apply that to Option and Result. What does exhaustiveness actually buy you here, compared with a language that uses null?
The point of exhaustiveness here is that absence and failure are ordinary enum variants, so the rule you already know — a match must cover every variant — forces the missing case into the open at the moment you read the value. You can handle it, default it with unwrap_or, or defer it to your caller with ?, but you cannot silently skip it. Every combinator in this lesson is shorthand for a match you would otherwise write out: unwrap_or is a match with a default arm, map is a match that leaves None untouched, and ? is a match that hands the failing arm back to the caller.
The dangerous version of "handling" a failure is one that handles it by erasing it. The next program does exactly that, and the giveaway is subtle — it compiles without a warning and prints a total that looks right. Commit a hypothesis about which line throws the information away before you change anything:
Debug
total_recorded should skip blank entries but report a malformed entry as an error. It compiles cleanly and its totals look plausible, but one of the two calls returns Ok when it should return Err. Say which line erases the failure and why, then fix it.
/// Total the scores that were recorded, ignoring blank entries.
/// A malformed entry is a data error and must NOT be silently counted as zero.
fn total_recorded(entries: &[&str]) -> Result<u32, String> {
let mut total = 0;
for entry in entries {
let trimmed = entry.trim();
if trimmed.is_empty() {
continue;
}
total += trimmed.parse::<u32>().ok().unwrap_or(0);
}
Ok(total)
}
fn main() {
let good = ["10", "", "32", " "];
let bad = ["10", "oops", "32"];
println!("good -> {:?}", total_recorded(&good));
println!("bad -> {:?}", total_recorded(&bad));
assert_eq!(total_recorded(&good), Ok(42), "blank entries should be skipped");
assert!(
total_recorded(&bad).is_err(),
"a malformed entry must be reported as an error, not counted as zero"
);
println!("All checks passed.");
}Expected output: good -> Ok(42)
bad -> Err("'oops' is not a number")
All checks passed.
The line that erases the failure is total += trimmed.parse::<u32>().ok().unwrap_or(0);. parse returns a Result; .ok() converts it to an Option and throws the error away; .unwrap_or(0) then turns the resulting None into a plain zero. So "oops" is silently counted as 0 and the function reports Ok(42) for data it should have rejected — the same total as the good input, which is exactly why this survives review. The fix is to propagate rather than erase: total += trimmed.parse::<u32>().map_err(|_| format!("'{}' is not a number", trimmed))?;. Reach for .ok() only when you have genuinely decided the error carries no information you need — pairing it with unwrap_or converts a failure into a believable number, which is the worst of the three outcomes.
Converting Between Option and Result
Because Option and Result model related concepts, the standard library provides easy conversions:
// Option → Result
let opt: Option<i32> = Some(42);
let res: Result<i32, &str> = opt.ok_or("missing value");
// Result → Option (discards the error)
let res2: Result<i32, &str> = Ok(42);
let opt2: Option<i32> = res2.ok();
ok_or is particularly useful when you want to treat a missing value as an error in a Result-returning function.
Try It Yourself
Reading about combinators is not the same as reaching for the right one under your own name. This is a build task: a small program that reports its own pass/fail. Three functions are stubbed out — one returns an Option, one returns a Result with two distinct error messages, and one collapses that Result into a plain number with a fallback. Run the starter as-is and it fails immediately, naming the first check that did not pass. Implement each until every check passes and it prints All checks passed.
The three signatures are the shape of every real config reader: absence is an Option, failure is a Result that says what failed, and a caller who does not care gets a default. The error strings are asserted exactly, so read the two format! templates in the comments carefully — a mismatched message is a failing check, not a stylistic difference.
Build
Finish the build. Three functions are stubbed out and the checks below them fail until each one returns the right value. Run it as-is to see which check fails first, decide what that function is missing, then implement all three until it prints 'All checks passed.' The checks run top to bottom, so the first failure you see is TODO 1 — implement it first, then work down. Do not change the signatures: which of Option, Result and a plain u32 each function returns is the exercise.
// A tiny config reader. The config is a list of "key=value" lines.
// TODO 1: find the value for key, or None if no line has that key.
// Split each line once on '=', compare the key half, return the value half
// as an owned String. lookup(&["a=1"], "a") -> Some("1".to_string())
// Hint: str has a split_once('=') method returning Option<(&str, &str)>.
fn lookup(lines: &[&str], key: &str) -> Option<String> {
let _ = lines;
let _ = key;
None
}
// TODO 2: return the value for key parsed as a u32, or an Err naming
// the failure. The two messages are asserted EXACTLY:
// missing key -> format!("missing key '{}'", key)
// bad number -> format!("key '{}' is not a number: '{}'", key, raw)
// Reach for lookup, ok_or_else and map_err. No unwrap, no panic.
fn read_number(lines: &[&str], key: &str) -> Result<u32, String> {
let _ = lines;
let _ = key;
Ok(0)
}
// TODO 3: return the value for key if present and parseable, else fallback.
// This one can never fail — it returns a plain u32.
// One call to read_number plus one combinator is all it takes.
fn read_number_or(lines: &[&str], key: &str, fallback: u32) -> u32 {
let _ = lines;
let _ = key;
let _ = fallback;
0
}
// --- Build checks: these must all pass. Do not edit below this line. ---
fn main() {
let config = ["port=8080", "retries=3", "host=localhost", "timeout=abc"];
assert_eq!(lookup(&config, "host"), Some("localhost".to_string()), "lookup should find an existing key");
assert_eq!(lookup(&config, "nope"), None, "lookup should return None for a missing key");
assert_eq!(read_number(&config, "port"), Ok(8080), "read_number should parse a present numeric value");
assert_eq!(
read_number(&config, "nope"),
Err("missing key 'nope'".to_string()),
"a missing key should be an Err naming the key"
);
assert_eq!(
read_number(&config, "timeout"),
Err("key 'timeout' is not a number: 'abc'".to_string()),
"an unparseable value should be an Err naming key and value"
);
assert_eq!(read_number_or(&config, "retries", 1), 3, "a good value wins over the fallback");
assert_eq!(read_number_or(&config, "timeout", 30), 30, "a bad value falls back");
assert_eq!(read_number_or(&config, "nope", 7), 7, "a missing key falls back");
println!("All checks passed.");
println!("host: {:?}", lookup(&config, "host"));
println!("port: {:?}", read_number(&config, "port"));
println!("timeout: {:?}", read_number(&config, "timeout"));
println!("timeout or 30: {}", read_number_or(&config, "timeout", 30));
}Expected output: All checks passed.
host: Some("localhost")
port: Ok(8080)
timeout: Err("key 'timeout' is not a number: 'abc'")
timeout or 30: 30
Once it passes, try two variations and predict each before running:
- Use
?on anOptionin aResultfunction. Inread_number, replace the wholeok_or_else(...)?call with a barelet raw = lookup(lines, key)?;. Predict what happens before running. It does not compile:error[E0277]: the ? operator can only be used on Results, not Options, in a function that returns Result, and rustc even suggests "use.ok_or(...)?to provide an error compatible withResult<u32, String>".?returns early from this function, so what it bails out with must fit this function's return type — the exact constraint from the?section above. - Swap
unwrap_orforunwrap_or_default. Inread_number_or, change the body toread_number(lines, key).unwrap_or_default(). Predict which check breaks before running. It compiles (with a warning thatfallbackis now unused) and fails the checka bad value falls back, withleft: 0, right: 30—unwrap_or_defaultsuppliesu32::default(), which is0, not the caller's fallback. A default that is silently zero is how a config bug becomes a production incident.
Key Takeaways
Option<T>replaces null: useSome(value)orNoneto represent optional data.Result<T, E>carries recoverable failure in the return type: useOk(value)orErr(error)for fallible operations, and leavepanic!for the unrecoverable case.matchhandles both types exhaustively; combinators likemap,and_then, andunwrap_orkeep code concise.- The
?operator propagates errors (orNone) early, eliminating most boilerplate error-forwarding code. - Convert between the two with
.ok()(Result → Option) and.ok_or(e)(Option → Result). - Prefer descriptive custom error types over plain
Stringerrors in library code. - Never use
.unwrap()in production code paths; always handle or propagate errors explicitly.
Pro Tip: Reach for
and_thenwhen you need to chain multipleOption- orResult-returning operations. It reads like a pipeline: each step only runs if the previous one succeeded, and the first failure short-circuits the whole chain — giving you the same guarantees as the?operator but as a functional expression you can embed in an iterator chain or assignment.
Next Steps
Now that you understand Option and Result, you're ready to learn about error handling in depth — including custom error types, the ? operator in practice, and strategies for robust error management.
Next lesson
Error Handling
Learn Rust error handling with the Result type, panic!, recoverable vs unrecoverable errors, and the ? operator for propagation
20 min