The Analogy: The Tender Box
A council's tender box holds one sealed envelope per invited firm. From the outside every envelope is identical -- same size, same weight in the hand. What you cannot tell by looking is whether there is a bid inside or whether the firm withdrew and returned an empty envelope, which the rules require them to do so that the clerk knows they were asked.
So the opening procedure is not optional. The clerk opens each envelope in front of a witness and writes down one of exactly two things: the amount, or the words "no bid". There is no third outcome, and there is no shortcut to the total that skips an envelope. It is slower than reading a column of numbers. It is also the only reason the total can be trusted.
The council used to keep a spreadsheet instead. A withdrawn firm was entered as 0, because the column had to contain a number and 0 was the obvious stand-in for nothing. That held up until the year a demolition firm genuinely bid 0, wanting the job for the salvage value alone -- and the spreadsheet had no way to tell the two zeros apart. The contract went to a firm that had already withdrawn and gone home.
That is the bug Rust designs out of existence. Absence is not a special value hidden inside the type -- not 0, not -1, not an empty string, not a null pointer. It is a second, visible state belonging to a different type: Option<T> is either Some(T) or None, and the compiler will not let you read the amount until you have said which one you are holding. You have to open the envelope.
Syntax or Core Structure
Option is not a keyword or a compiler feature. It is an ordinary two-variant enum in the standard library, and it is in the prelude, so Some and None need no import and no path.
fn main() {
let present: Option<i32> = Some(7);
let absent: Option<i32> = None;
println!("present = {present:?}");
println!("absent = {absent:?}");
// The way in is to say what you will do about each case.
match present {
Some(n) => println!("match: got {n}"),
None => println!("match: nothing"),
}
// if let, when only one arm is interesting.
if let Some(n) = absent {
println!("if let: got {n}");
} else {
println!("if let: nothing");
}
// Or stay outside the envelope entirely and work through it.
let doubled: Option<i32> = present.map(|n| n * 2);
let fallback: i32 = absent.unwrap_or(-1);
println!("doubled = {doubled:?}");
println!("fallback = {fallback}");
// Absence turns up wherever an operation might not produce a value.
let names = ["ada", "grace", "linus"];
println!("names.first() = {:?}", names.first());
println!("names.get(9) = {:?}", names.get(9));
println!("parse ok = {:?}", "42".parse::<i32>().ok());
println!("parse bad = {:?}", "4x".parse::<i32>().ok());
println!("find a space = {:?}", "no-spaces".find(' '));
}
Output:
present = Some(7)
absent = None
match: got 7
if let: nothing
doubled = Some(14)
fallback = -1
names.first() = Some("ada")
names.get(9) = None
parse ok = Some(42)
parse bad = None
find a space = None
The mechanism that makes all of this safe is the plainest possible one: Option<i32> and i32 are different types, so a value that might be missing cannot be passed anywhere a definite value is expected.
fn main() {
let dims = [3u32, 4, 5];
let first: u32 = dims.first();
println!("{first}");
}
Output:
error[E0308]: mismatched types
--> src/main.rs:3:22
|
3 | let first: u32 = dims.first();
| --- ^^^^^^^^^^^^ expected `u32`, found `Option<&u32>`
| |
| expected due to this
|
help: consider using `Option::expect` to unwrap the `Option<&u32>` value, panicking if the value is an `Option::None`
Two details in that message repay attention. The found type is Option<&u32>, not Option<u32> -- first hands back a borrow, because the array still owns its elements. And the suggested rewrite, which has been trimmed here, appends .expect("REASON"): rustc is telling you that it cannot decide what should happen when the array is empty, and that you must. That decision is the whole cost of the design, and it is charged exactly once, at the point where absence is possible.
Technical Depth: What It Costs and What It Gives
The definition, in full
pub enum Option<T> {
None,
Some(T),
}
That is the entire type. Everything else -- unwrap, map, and_then, the ? operator's behaviour on it -- is methods and trait impls written in Rust on top of those two variants. You could define it yourself, and the only thing you would lose is the prelude import and a handful of compiler niceties around ?.
It is usually free
An enum normally needs a tag to record which variant it holds. Option often does not, because many types leave bit patterns unused, and None can move into one of them. That unused pattern is called a niche.
use std::mem::size_of;
fn main() {
println!("u8 = {}", size_of::<u8>());
println!("Option<u8> = {}", size_of::<Option<u8>>());
println!("bool = {}", size_of::<bool>());
println!("Option<bool> = {}", size_of::<Option<bool>>());
println!("u64 = {}", size_of::<u64>());
println!("Option<u64> = {}", size_of::<Option<u64>>());
println!("&u64 = {}", size_of::<&u64>());
println!("Option<&u64> = {}", size_of::<Option<&u64>>());
println!("Box<u64> = {}", size_of::<Box<u64>>());
println!("Option<Box<u64>> = {}", size_of::<Option<Box<u64>>>());
println!("String = {}", size_of::<String>());
println!("Option<String> = {}", size_of::<Option<String>>());
}
Output (on a 64-bit target):
u8 = 1
Option<u8> = 2
bool = 1
Option<bool> = 1
u64 = 8
Option<u64> = 16
&u64 = 8
Option<&u64> = 8
Box<u64> = 8
Option<Box<u64>> = 8
String = 24
Option<String> = 24
Read the pairs against each other. bool uses two of its 256 byte values, so None takes a third and Option<bool> stays one byte. A reference and a Box are never null, so None takes the all-zeros pattern and both Option forms stay eight bytes -- which is exactly why Option<&T> and Option<Box<T>> are the correct way to describe a nullable pointer across an FFI boundary, with no wrapper and no cost. String hides its niche one level down, in the non-null pointer it owns. But u8 and u64 genuinely use every bit pattern they have, so Option must add a tag, and alignment rounds Option<u64> up from nine bytes to sixteen. That last row is the one to remember when a hot Vec<Option<u64>> doubles in size.
The vocabulary
Most Option code never opens the envelope at all; it applies a method and keeps going. Learning this table is most of learning Option.
| Method | Shape | What comes back | Can panic |
|---|---|---|---|
unwrap() | Option<T> to T | the value | yes, on None |
expect(msg) | Option<T> to T | the value | yes, with your message |
unwrap_or(d) | Option<T> to T | the value, else d | no |
unwrap_or_else(f) | Option<T> to T | the value, else f() | no |
unwrap_or_default() | Option<T> to T | the value, else T::default() | no |
map(f) | Option<T> to Option<U> | f applied inside the Some | no |
and_then(f) | Option<T> to Option<U> | one lookup fed into the next | no |
filter(p) | Option<T> to Option<T> | None unless p holds | no |
or(b) and or_else(f) | Option<T> to Option<T> | the first Some of the two | no |
zip(b) | Option<T> to Option<(T, U)> | Some only if both are | no |
take() | &mut Option<T> to Option<T> | the value, leaving None behind | no |
replace(v) | &mut Option<T> to Option<T> | the displaced value | no |
as_ref() and as_mut() | &Option<T> to Option<&T> | a borrow of the inside | no |
is_some() and is_none() | &Option<T> to bool | the question, and nothing else | no |
ok_or(e) | Option<T> to Result<T, E> | the bridge to error handling | no |
The two rows people confuse are map and and_then. Use map when your closure returns a plain value; use and_then when it returns another Option. Getting it backwards leaves you holding an Option<Option<T>>, which the compiler will point out immediately.
The vocabulary in use
struct User {
name: String,
manager: Option<String>,
seats: Option<u32>,
}
fn main() {
let staff = vec![
User { name: String::from("ada"), manager: None, seats: Some(3) },
User { name: String::from("grace"), manager: Some(String::from("ada")), seats: None },
User { name: String::from("linus"), manager: Some(String::from("ada")), seats: Some(0) },
];
for u in &staff {
// as_ref borrows the inside; map works there without opening anything.
let shouted = u.manager.as_ref().map(|m| m.to_uppercase());
// unwrap_or_else builds the default only when it is needed.
let boss = shouted.unwrap_or_else(|| String::from("(none)"));
// filter turns a meaningless Some into None.
let real_seats = u.seats.filter(|n| *n > 0);
// and_then feeds one lookup into another.
let initial = u.manager.as_ref().and_then(|m| m.chars().next());
println!(
"{:<6} boss {:<8} seats {:?} initial {:?}",
u.name, boss, real_seats, initial
);
}
// Whole collections, without a loop and without an unwrap.
let total: u32 = staff.iter().filter_map(|u| u.seats).sum();
let any_missing = staff.iter().any(|u| u.seats.is_none());
let all_managed: Option<Vec<&String>> =
staff.iter().map(|u| u.manager.as_ref()).collect();
println!();
println!("total seats = {total}");
println!("any missing = {any_missing}");
println!("all managed = {all_managed:?}");
}
Output:
ada boss (none) seats Some(3) initial None
grace boss ADA seats None initial Some('a')
linus boss ADA seats None initial Some('a')
total seats = 3
any missing = true
all managed = None
Two lines there do more than they look like they do. filter_map(|u| u.seats) drops the None entries and unwraps the rest in one pass, which is why the total is 3 rather than a panic. And the collect into Option<Vec<&String>> is the all-or-nothing form: it short-circuits at the first None and returns None for the whole collection, so all_managed is None because ada has no manager. Swap the target type to Vec<Option<&String>> and you get the per-element answers instead. Note also that linus has Some(0) seats and prints None -- filter is where the lesson's whole point lives, because zero seats and unknown seats are different facts and this code keeps them different.
Reading, mutating and emptying in place
fn main() {
let mut slot: Option<String> = Some(String::from("job-1"));
// Read through a borrow: slot keeps ownership of the String.
println!("len = {:?}", slot.as_ref().map(|s| s.len()));
// Mutate the value where it lives.
if let Some(s) = slot.as_mut() {
s.push_str("-retry");
}
println!("after mut = {slot:?}");
// take() moves the value out and leaves None behind.
let taken = slot.take();
println!("taken = {taken:?}");
println!("slot = {slot:?}");
// replace() installs a new value and hands back the old one.
let mut counter: Option<u32> = None;
let old = counter.replace(1);
println!("old = {old:?}, counter = {counter:?}");
}
Output:
len = Some(5)
after mut = Some("job-1-retry")
taken = Some("job-1-retry")
slot = None
old = None, counter = Some(1)
take is the method to reach for whenever you need to move a value out of a struct field you only have a &mut to. The borrow checker will not let you move out of a borrow, but it will let you swap in a None, which is precisely what take does -- and it is how nearly every hand-written linked list, iterator and state machine in Rust hands a value along.
The ? operator works on Option too
fn initial_of_manager(u: &User) -> Option<char> {
let m = u.manager.as_ref()?; // returns None from the function on None
m.chars().next()
}
Inside a function that itself returns Option, ? unwraps a Some and returns None early otherwise. It is the same operator you will meet again on Result in the error-handling module, and the resemblance is not a coincidence -- both types mean "there may be nothing here to continue with".
Real World Example: A Configuration That Layers Its Defaults
Almost every program answers the same question three or four times over: what is the port? The command line may say. The environment may say. A config file may say. Something has to say. Option is the type that means "this layer did not say", which is a completely different fact from "this layer said zero".
#[derive(Debug, Default)]
struct Partial {
host: Option<String>,
port: Option<u16>,
workers: Option<u32>,
verbose: Option<bool>,
}
#[derive(Debug)]
struct Config {
host: String,
port: u16,
workers: u32,
verbose: bool,
}
impl Partial {
// Fields set on self win; fields left None fall through to lower.
fn over(self, lower: Partial) -> Partial {
Partial {
host: self.host.or(lower.host),
port: self.port.or(lower.port),
workers: self.workers.or(lower.workers),
verbose: self.verbose.or(lower.verbose),
}
}
// The boundary: every Option is answered exactly once, here.
fn resolve(self) -> Config {
Config {
host: self.host.unwrap_or_else(|| String::from("127.0.0.1")),
port: self.port.unwrap_or(8080),
// Zero workers is not a choice anybody made on purpose.
workers: self.workers.filter(|n| *n > 0).unwrap_or(4),
verbose: self.verbose.unwrap_or(false),
}
}
}
Each source produces a Partial, and each one is free to say nothing about any field.
fn from_file() -> Partial {
Partial {
host: Some(String::from("0.0.0.0")),
port: Some(9000),
workers: Some(0),
verbose: None,
}
}
fn from_env(vars: &[(&str, &str)]) -> Partial {
let get = |k: &str| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| *v);
Partial {
host: get("APP_HOST").map(String::from),
port: get("APP_PORT").and_then(|v| v.parse().ok()),
workers: get("APP_WORKERS").and_then(|v| v.parse().ok()),
verbose: get("APP_VERBOSE").map(|v| v == "1"),
}
}
fn from_args(args: &[&str]) -> Partial {
let mut p = Partial::default();
let mut it = args.iter();
while let Some(a) = it.next() {
match *a {
"--host" => p.host = it.next().map(|v| String::from(*v)),
"--port" => p.port = it.next().and_then(|v| v.parse().ok()),
"-v" => p.verbose = Some(true),
_ => {}
}
}
p
}
fn main() {
let file = from_file();
let env = from_env(&[("APP_PORT", "7000"), ("APP_WORKERS", "twelve")]);
let args = from_args(&["--host", "example.test", "-v"]);
println!("file = {file:?}");
println!("env = {env:?}");
println!("args = {args:?}");
// Highest precedence on the left.
let merged = args.over(env).over(file);
println!("merged = {merged:?}");
println!("config = {:?}", merged.resolve());
}
Output:
file = Partial { host: Some("0.0.0.0"), port: Some(9000), workers: Some(0), verbose: None }
env = Partial { host: None, port: Some(7000), workers: None, verbose: None }
args = Partial { host: Some("example.test"), port: None, workers: None, verbose: Some(true) }
merged = Partial { host: Some("example.test"), port: Some(7000), workers: Some(0), verbose: Some(true) }
config = Config { host: "example.test", port: 7000, workers: 4, verbose: true }
The merge is four lines long because or is exactly the operation the problem calls for: keep mine if I have one, otherwise take yours. Three layers compose by folding right to left, and no layer needs to know how many other layers exist or what any of them decided. The command line supplied the host, the environment supplied the port, the file supplied nothing that survived, and none of that logic appears anywhere except in the four or calls.
Watch where the bad value dies. The file said workers: Some(0), which is a real answer, so the merge correctly kept it -- or has no opinion about whether zero is sensible. It was filter(|n| *n > 0) in resolve that rejected it, in the one function that knows what a valid worker count is. Had Partial::workers been a plain u32 with 0 meaning "unset", the file's genuine mistake and the absence of an answer would have been the same value, and the program would have started with zero workers or silently ignored a deliberate 0. That is the tender box's spreadsheet, reproduced in a config loader.
The two structs are the real lesson. Partial has an Option on every field; Config has none. Once resolve has returned, nothing downstream ever asks again whether the port was configured, because the type it is holding cannot express that question. The uncertainty is confined to a single function at the edge of the program, and everything inside it works with definite values -- which is the shape people mean when they say "parse, don't validate".
Two rough edges worth naming. APP_WORKERS=twelve was silently discarded by .ok(): the loader treated an unparseable value exactly like an absent one, which is convenient and wrong, and it is the case Result exists to handle properly in the error-handling module. Similarly get("APP_VERBOSE").map(|v| v == "1") maps APP_VERBOSE=yes to Some(false) -- a confident "no" rather than an honest "I could not read that". And or is eager: args.over(env).over(file) constructs every layer even though the command line wins the host outright. With a source that costs a disk read, or_else and a closure would defer the work.
Common Mistakes
- Reaching for
unwrap()by reflex. It compiles, it works on the happy path, and when it fails the panic readscalled Option::unwrap() on a None valuefollowed by a line number -- nothing about what was being looked up or why.expect("no config file at CODEX_CONFIG")costs one line and turns a mystery into a bug report.
- Checking with
is_some()and then unwrapping.if x.is_some() { use(x.unwrap()) }performs the test twice, and the second test is the one that can panic.if let Some(v) = xperforms it once and hands you the value, which is why it exists.
- Keeping a sentinel alongside the
Option. Aport: Option<u16>whereSome(0)means "unset" has reinvented the problem inside the solution. If a value is invalid,filterit out; if it is absent, that isNone.
- Passing an expensive expression to
unwrap_or.cache.get(k).unwrap_or(load_from_disk(k))reads the disk on every call, hit or miss, because arguments are evaluated before the call.unwrap_or_else(|| load_from_disk(k))runs it only on a miss.
- Cloning to escape a borrow.
opt.clone().unwrap()to read a length, whenopt.as_ref().map(|s| s.len())reads it for free.as_refexists specifically so that inspecting anOptioncosts nothing.
- Nesting matches instead of chaining. Four levels of
match ... { Some(x) => match ... }says the same thing as oneand_thenchain, in four times the space, with four chances to write theNonearm wrong.
- Using
mapwhereand_thenbelongs. If the closure returns anOption,mapgives youOption<Option<T>>. The compiler catches it, but the fix people reach for is.flatten()on the end rather than theand_thenthat was wanted.
- Assuming the wrapper always costs a word.
Option<&T>andOption<Box<T>>are free;Option<u64>is twice the size ofu64. Wrapping a large struct in anOptioninside a hotVecis where this actually shows up, andsize_ofanswers it in one line.
- Using
OptionwhereResultwas needed.Nonerecords that something did not happen and throws away why. A parse failure, a missing file and a permissions error all become the sameNone, and.ok()is the exact line where that information was discarded.
Best Practices
- Let the type carry the absence. Never a sentinel, never a magic index, never an empty string standing in for "not set" -- that is the class of bug
Optionwas added to eliminate.
- Answer every
Optiononce, at the boundary, and hand the inside of the program a type with no options in it. Oneresolvebeats fiftyunwrap_orcalls scattered downstream.
- When you do unwrap, use
expectwith a message naming the invariant you believe holds. "Should never happen" is not a message; "template registry is populated in main before any request" is.
- Prefer
unwrap_or_elseoverunwrap_orwhenever the default costs anything to build, andunwrap_or_defaultwhenT::default()is already the right answer.
- Use
as_refandas_mutto inspect or edit in place, andtakeorreplaceto move a value out of a struct field you only hold by&mut.
- Chain with
map,and_thenandfilterrather than nesting matches. The chain reads in the same order as the path it walks, and there is noNonearm to get wrong.
- Collect into
Option<Vec<T>>when the requirement is genuinely all-or-nothing, and intoVec<Option<T>>when the caller needs to see which elements were missing.
- Convert to
Resultwithok_ororok_or_elsethe moment a caller deserves to know why there was nothing there.Optionis for absence, not for failure.
Practice Exercises
- Retire the sentinel. Start from
fn index_of(xs: &[i32], target: i32) -> i32which returns-1when the target is missing, and a caller that tests the result withif found > 0. Rewrite the function to returnOption<usize>and the caller to useif let. Then run both versions on a slice whose first element is the target, and explain which one was already broken and why the type change makes that bug unwritable.
- Combinator drill. Define
struct Order { customer: Option<Customer> },struct Customer { address: Option<Address> }andstruct Address { postcode: Option<String> }. Writefn postcode(o: &Order) -> Option<&str>twice -- once with three nestedmatchexpressions, once as a singleand_thenchain -- and check that both give identical answers for an order with everything, one missing the postcode, and one missing the customer. Finish withfn postcode_or(o: &Order) -> &strthat falls back to"UNKNOWN".
- A reusable slot. Write
struct Slot { current: Option<String>, swaps: u32 }withfn put(&mut self, v: String) -> Option<String>returning whatever it displaced,fn clear(&mut self) -> Option<String>, andfn peek(&self) -> Option<&str>. Implementputwithreplaceandclearwithtake, use nocloneanywhere, and incrementswapsonly whenputactually displaced a value. Print the slot's state afterput,put,clear,peek.
- Extend the loader. Add
tls: Option<bool>andcert_path: Option<String>toPartial, and makeresolvefall back to TLS off when TLS is requested without a certificate path. Add a fourth layer of highest precedence for hard-coded overrides, then print the resolvedConfigfor three different combinations of layers. Write one sentence explaining whyoris the right operator insideoverandunwrap_oris the right one insideresolve.