Option is not a nullable: sentinels, defaults and missing data
Reviewing AI-written Rust warns against unwrap(), which turns a missing value into a panic. That lesson is easy to over-learn. The quickest way to obey it is to remove the panic by inventing a value instead, and coding assistants reach for that readily: unwrap_or_default(), unwrap_or(0), -1 for “not found”, an empty string for “missing”. The code compiles and never panics. The missing case has gone from the types, though, and now the data is wrong instead of the program stopping.
Both failures have the same root: nobody decided what absence means. This article is about deciding. Every example compiles without warnings, and Clippy’s default lints say nothing about any of them (with the Rust version shown above); the compile check has the evidence. The examples were written by hand to show the patterns.
What Option says
Option<T> is an enum, a type whose value is exactly one of a fixed list of variants. It has two: Some(value), holding a T, and None. A function that returns Option<usize> cannot hand back a bare number, and its caller cannot use the result as one without first saying what happens on None.
That much will sound familiar if you use C#’s nullable types or TypeScript with strictNullChecks: both put absence into the type too. The habit they share is to treat absence as an obstacle and remove it as early as possible: ?? 0 in C# and TypeScript, or "" in Python. The same habit in Rust is unwrap_or(0).
The title’s point is that None is information, not an obstacle. One sign that Option is a value in its own right is that it nests. In TypeScript, string | undefined | undefined is the same type as string | undefined. In C#, the underlying type of a nullable value type cannot itself be nullable, so int?? does not exist. In Rust, Option<Option<String>> is a different type from Option<String>, with three distinct states. We will come back to when that is useful.
Option has a cost, and it depends on T. The value has to record which variant it holds. Every bit pattern of a usize is a valid number, so Option<usize> needs extra room for that record and is larger than a usize. A reference can never be null, though, so Option<&T> can use the null address for None.
Sentinels: -1, "" and 0
A sentinel is an ordinary value of a type, set aside by convention to mean “no value”. Java’s String.indexOf, C#’s String.IndexOf, Go’s strings.Index and Python’s str.find all return -1 when they find nothing. Ported to Rust, that looks like this:
pub fn find_index(names: &[&str], wanted: &str) -> i32 {
for (i, name) in names.iter().enumerate() {
if *name == wanted {
return i as i32;
}
}
-1
}The convention lives in the documentation, not the type, so nothing makes a caller check for -1. There is a second, quieter problem. as converts between number types and never fails: when the value does not fit, it truncates. On a 64-bit machine, an index of 2³² comes back as 0. That is unlikely with a list of names and entirely possible with a large file of records.
Rust’s standard library answers “where is it?” with an Option: Iterator::position, str::find, slice::first and HashMap::get all return one. So:
pub fn find_index(names: &[&str], wanted: &str) -> Option<usize> {
names.iter().position(|name| *name == wanted)
}An empty string works the same way:
pub struct Customer {
pub name: String,
pub email: String, // empty if we have no address
}
pub fn reminder_recipients(customers: &[Customer]) -> Vec<&str> {
customers.iter().map(|c| c.email.as_str()).collect()
}Every reader of email must know the convention, and this one forgot, so "" goes off to the mail system. In the version below, filter_map keeps the Some values and drops the Nones, and as_deref turns a borrowed Option<String> into an Option<&str> without copying the string:
pub struct Customer {
pub name: String,
pub email: Option<String>,
}
pub fn reminder_recipients(customers: &[Customer]) -> Vec<&str> {
customers
.iter()
.filter_map(|c| c.email.as_deref())
.collect()
}Is a sentinel ever right? Sometimes it is forced on you: a C library returns -1, or a file format stores 0 for “unknown”. Convert at that boundary, so that the rest of the program sees an Option.
unwrap_or_default(): true or convenient?
unwrap_or_default() returns the value inside a Some, or else the type’s default value from the Default trait (a trait is a named set of methods a type can implement, much like an interface): 0 for numbers, an empty String, false, an empty Vec. It is the tidiest way to make an Option go away, and Clippy’s default lints encourage it: unwrap_or_default, in the style group, suggests it in place of unwrap_or_else(String::new), and manual_unwrap_or_default, in suspicious, suggests it in place of a match whose None arm returns 0. Those lints are about spelling. Neither can tell whether the default is true.
pub fn coldest(readings: &[i32]) -> i32 {
readings.iter().copied().min().unwrap_or_default()
}A sensor that reported nothing now reads 0 °C. That is a perfectly plausible temperature, so nothing downstream can tell “no data” from “freezing”. Return the Option, and let the code that knows what to show decide:
pub fn coldest(readings: &[i32]) -> Option<i32> {
readings.iter().copied().min()
}
pub fn describe(readings: &[i32]) -> String {
match coldest(readings) {
Some(celsius) => format!("coldest: {celsius} °C"),
None => "no readings".to_string(),
}
}Some defaults are true. Summing an empty list of integers gives 0, and the standard library’s sum says so: 0 is the additive identity, the value that changes nothing when you add it. min and max return an Option, because the smallest of nothing has no answer. The longest_line function in Read the compiler error ends with .max().unwrap_or(0), and that is fine: if you are sizing a column, zero bytes is exactly the right width for no lines. It is the same shape of code as coldest, and a different truth.
A default can also be part of the contract:
pub const DEFAULT_RETRIES: u32 = 3;
pub fn retries(configured: Option<u32>) -> u32 {
configured.unwrap_or(DEFAULT_RETRIES)
}It is named, documented and kept in one place. So it depends on what the value claims. A default is sound when it is the identity of the operation (a sum of 0, a count of 0, an empty list) or a documented behaviour. It is suspect when it is a plausible member of the domain standing in for “unknown”: 0 °C, an empty email address, or 1 January 1970 as a last login.
Nested and optional containers
Option<Option<T>>
A partial update is the classic case for three states. JSON Merge Patch works this way: a field missing from the patch leaves the target alone, and a field set to null removes it. In Rust:
pub struct Profile {
pub nickname: Option<String>,
}
impl Profile {
pub fn apply(&mut self, nickname: Option<Option<String>>) {
if let Some(change) = nickname {
self.nickname = change;
}
}
}This is correct, but None means “keep” and Some(None) means “clear” only by convention. Clippy’s option_option lint suggests an enum with names for the three cases:
pub enum Change<T> {
Keep,
Clear,
Set(T),
}
impl Profile {
pub fn apply(&mut self, nickname: Change<String>) {
match nickname {
Change::Keep => {}
Change::Clear => self.nickname = None,
Change::Set(name) => self.nickname = Some(name),
}
}
}The nesting is noise when no code treats the two kinds of absence differently. If “no such user” and “user without a nickname” are both shown as the user’s name, call flatten() where the nested value appears. It turns Option<Option<T>> into Option<T>, with both kinds of absence becoming None, and the rest of the code deals in one Option.
Option<bool>
Three states again: yes, no, and not answered. Whether the third state matters depends on the question:
pub fn may_email(opted_in: Option<bool>) -> bool {
opted_in.unwrap_or(false)
}
pub fn should_ask(opted_in: Option<bool>) -> bool {
opted_in.is_none()
}For “may we send marketing email?”, not asked and refused get the same answer, so unwrap_or(false) is true there. For “should we ask?”, they differ. When the distinction matters, an enum with NotAsked, Refused and Given reads better than remembering what None stands for. When every caller writes unwrap_or(false), the field should be a bool.
Option<Vec<T>>
None and an empty Vec can mean “not loaded” and “loaded, and there are none”. If a screen shows a spinner for the first and “no tags” for the second, keep the Option. If no code ever treats them differently, use a plain Vec<T>. Creating an empty vector with Vec::new() does not allocate, so Option saves almost nothing here and adds a question to every use.
Several Options that must agree
pub struct Delivery {
pub dispatched_at: Option<u64>,
pub delivered_at: Option<u64>,
pub tracking_number: Option<String>,
pub failure_reason: Option<String>,
}The timestamps are seconds since 1970. Four independent Options allow 2⁴ = 16 combinations of present and absent, and the business has four states. A parcel delivered without ever being dispatched is representable, and so is one that was delivered and failed. Every function that reads a Delivery either checks for those or quietly assumes they never happen. An enum lists the states that exist:
pub enum Delivery {
Pending,
Dispatched {
at: u64,
tracking: String,
},
Delivered {
dispatched_at: u64,
delivered_at: u64,
tracking: String,
},
Failed {
reason: String,
},
}
impl Delivery {
pub fn tracking(&self) -> Option<&str> {
match self {
Delivery::Dispatched { tracking, .. } | Delivery::Delivered { tracking, .. } => {
Some(tracking)
}
Delivery::Pending | Delivery::Failed { .. } => None,
}
}
}tracking() still returns an Option, because “a pending parcel has no tracking number” is a true answer. The enum makes invalid states unrepresentable: the contradictions above can no longer be built.
It has costs. Every use becomes a match, the type no longer maps directly to a row of nullable database columns or a flat JSON object, and stored data may need migrating. When the fields really are independent, such as an optional phone number and an optional nickname, separate Options are the right model. The question is whether the fields must agree with each other.
Reviewing defaults
For every invented value in a change, whether it is unwrap_or, unwrap_or_default(), -1 or "", ask:
- Is this value true, or just convenient?
- Could a reader of the output tell it from real data? 0 °C, no; “no readings”, yes.
- Is it an identity or a documented contract? Then it is fine. Give it a name.
- Who should decide? Usually the code nearest the user. Return the
Optionand let it. - Do several
Options have to agree? Then they are probably one enum.
A search finds the candidates, though not the answers:
grep -rnE 'unwrap_or|-1\b' src/Clippy’s default lints say nothing about any example here. Switching on the pedantic group adds a warning about the as cast in find_index, but not about the -1. Whether a default is true depends on what the data means, and no lint knows that. Module 2 of Rust Primer, Data modelling with Option and Result, practises exactly this: replacing nulls, exceptions, sentinel values and stringly errors with types that state the contract.