Module 6 · Nullability & error handling
6.1Option instead of null
How Rust replaces null with Option, which methods do the work of ?. and ??, and why a missing value can't slip past the compiler.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A value that may be missing | T | undefined (or T | null) | T? | Option<T>: Some(value) or None |
| Use a fallback | value ?? fallback | value ?? fallback | value.unwrap_or(fallback) |
| Reach inside if it's there | user?.address?.city | user?.Address?.City | map and and_then, or ? inside a function that returns Option |
| Using it without checking | Compile error with strictNullChecks | Warning CS8602; an error only if you make nullable warnings errors | Compile error. An Option<T> is not a T |
| "Trust me, it's there" | value!: no check at run time | value!: no check at run time | value.expect("why"): checks, and panics right there if it's None |
Tony Hoare called the null reference, which he added to ALGOL W in 1965, his “billion-dollar mistake”: any reference might point at nothing, and you find out when the program crashes. Rust has no null. A value that might be missing has its own type, Option<T>, and the compiler won’t let you use it as a T until you’ve said what happens when it isn’t there. TypeScript with strictNullChecks gets close to this, so much of this lesson will feel familiar. The new parts are where Rust closes the gaps, and the methods that replace ?. and ??.C#‘s nullable reference types get part of the way there, with warnings. This lesson shows where Rust goes further, and which methods replace ?. and ??.
A missing value has its own type
You met Option in Enums with data: an ordinary enum with two variants, Some(value) and None. Here it is in its most common job, a lookup that might find nothing:
type User = { id: number; name: string };
function findUser(users: User[], id: number): User | undefined {
return users.find((user) => user.id === id);
}
const users: User[] = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
for (const id of [2, 7]) {
const user = findUser(users, id);
if (user !== undefined) {
console.log(`${id}: ${user.name}`);
} else {
console.log(`${id}: no such user`);
}
}List<User> users = [new(1, "Ada"), new(2, "Grace")];
foreach (var id in new[] { 2, 7 })
{
var user = FindUser(users, id);
if (user is not null)
{
Console.WriteLine($"{id}: {user.Name}");
}
else
{
Console.WriteLine($"{id}: no such user");
}
}
static User? FindUser(List<User> users, int id) => users.Find(user => user.Id == id);
record User(int Id, string Name);struct User {
id: u32,
name: String,
}
fn find_user(users: &[User], id: u32) -> Option<&User> {
users.iter().find(|user| user.id == id)
}
fn main() {
let users = vec![
User {
id: 1,
name: String::from("Ada"),
},
User {
id: 2,
name: String::from("Grace"),
},
];
for id in [2, 7] {
match find_user(&users, id) {
Some(user) => println!("{id}: {}", user.name),
None => println!("{id}: no such user"),
}
}
}Output
2: Grace 7: no such user
find_user returns Option<&User>: either Some with a borrow of the matching user, or None. The match handles both. Now try to skip the check and read the name straight away:
let user = find_user(&users, 7);
println!("{}", user.name);Rust doesn't compile this: error E0609
error[E0609]: no field `name` on type `Option<&User>`
--> main.rs:2:21
|
2 | println!("{}", user.name);
| ^^^^ unknown field
|
help: one of the expressions' fields has a field of the same name
|
2 | println!("{}", user.unwrap().name);
| +++++++++An Option<&User> has no field called name, so this doesn’t compile. TypeScript also rejects findUser(users, 7).name, because the value is possibly undefined. So far the two languages agree.C# compiles FindUser(users, 7).Name with warning CS8602 (“Dereference of a possibly null reference”), then throws a NullReferenceException when it runs. Rust gives you no build to run.
Why a type beats a check you have to remember
TypeScript’s null checks are good, but they describe the program rather than control it, and there are ways around them:
value!tells the compiler “this isn’tundefined” and generates no check at all. If you were wrong, the failure shows up later, wherever the value is used.- Indexing an array gives you
T, notT | undefined, unless you turn onnoUncheckedIndexedAccess, whichstrictdoesn’t include. anyswitches checking off.JSON.parsereturnsany, so data from outside the program arrives unchecked.strictNullChecksis a setting. It’s on by default since TypeScript 6 (as part ofstrict), but code compiled with it turned off, or a declaration file written carelessly, saysstringand means “a string orundefined”.
Here’s the first one. The compiler is satisfied, and the value is still missing:
const names: string[] = [];
const first: string = names[0]!; // "trust me": no check is made
console.log(first === undefined);Output
true
C#‘s nullable reference types are annotations and warnings layered on a runtime where every reference can still be null:
- Warnings, not errors. The checks run only where
<Nullable>enable</Nullable>is on (new project templates turn it on), and unless a project also sets<WarningsAsErrors>nullable</WarningsAsErrors>, null-safety problems don’t stop the build. value!, the null-forgiving operator, silences the warning and generates no check.- Holes the compiler can’t see: a new array of
stringis full ofnulls,default!initializers, and libraries compiled without annotations. T?means two things.int?isNullable<int>, a separate struct with aHasValueflag.string?is the samestringtype with an annotation that changes nothing at run time.
Here’s the array hole. The type says string, it builds with no warning, and the value is null:
var names = new string[2];
Console.WriteLine(names[0] is null); // a "non-nullable" string that is nullOutput
True
Rust has none of these gaps, because there is no null value to leak in. A String is always a string; “maybe a string” is a different type, Option<String>. To get the String out, you must handle None: with match, with a method that supplies a fallback, or with unwrap() / expect(...), which check at run time and stop the program at that line if the value is missing. Even the “trust me” path is checked. Data from outside is no exception: when you parse JSON with serde_json (Module 13), you declare a field that may be absent as Option<T>, and a missing field that isn’t an Option is a parse error, not a silent null.
let names: Vec<String> = Vec::new();
let first = names.first(); // Option<&String>: no index, no panic
println!("{}", first.is_none());Output
true
Caught at compile timeThe check can't be forgotten
A missing value that slips through becomes a crash far from where it started, in code that trusted the type. In Rust, a function that returns Option<T> forces every caller to decide what None means before the program compiles. The decision is made once, where the value is produced, and every caller sees it in the signature.
Fallbacks: unwrap_or instead of ??
The most common thing to do with a missing value is to use a default instead. TypeScriptC#’s ?? becomes unwrap_or:
type Settings = { port?: number; host?: string };
function address(settings: Settings): string {
const port = settings.port ?? 8080;
const host = settings.host ?? "localhost";
return `${host}:${port}`;
}
console.log(address({ port: 3000 }));
console.log(address({ host: "example.com" }));Console.WriteLine(Address(new Settings(3000, null)));
Console.WriteLine(Address(new Settings(null, "example.com")));
static string Address(Settings settings)
{
var port = settings.Port ?? 8080;
var host = settings.Host ?? "localhost";
return $"{host}:{port}";
}
record Settings(int? Port, string? Host);struct Settings {
port: Option<u16>,
host: Option<String>,
}
fn address(settings: &Settings) -> String {
let port = settings.port.unwrap_or(8080);
let host = settings.host.as_deref().unwrap_or("localhost");
format!("{host}:{port}")
}
fn main() {
let local = Settings {
port: Some(3000),
host: None,
};
let public = Settings {
port: None,
host: Some(String::from("example.com")),
};
println!("{}", address(&local));
println!("{}", address(&public));
}Output
localhost:3000 example.com:8080
Two details:
settings.portis anOption<u16>, which isCopy, sounwrap_orcan take it by value.settings.hostis anOption<String>inside a borrowed struct.unwrap_ortakes the option by value, which would move theStringout ofsettings..as_deref()turns&Option<String>intoOption<&str>, a borrowed view, andunwrap_or("localhost")then picks between two&strs. For other types,.as_ref()turns&Option<T>intoOption<&T>.
unwrap_or has two relatives:
unwrap_or_else(|| ...)calls a closure only when the value isNone. Use it when the fallback costs something, like building aStringor calling a function.unwrap_or(value)evaluatesvaluebefore the call, every time, because it’s an ordinary argument. The??operator only evaluates its right side when it needs it, sounwrap_or_elseis the closer match when the fallback is a call.unwrap_or_default()uses the type’s default:0,false, an emptyStringor an emptyVec.
|| and ??. Some(0) and Some(String::new()) are values like any other; only None is missing.Reaching inside: map, and_then and ?
TypeScriptC# chains ?. to walk through values that might be missing. Rust has no ?. operator. Inside a function that returns an Option, you use ? instead:
type Address = { city: string };
type User = { id: number; name: string; address?: Address };
function cityOf(users: User[], id: number): string | undefined {
return users.find((user) => user.id === id)?.address?.city;
}
const users: User[] = [
{ id: 1, name: "Ada", address: { city: "London" } },
{ id: 2, name: "Grace" },
];
for (const id of [1, 2, 3]) {
console.log(`${id}: ${cityOf(users, id) ?? "unknown"}`);
}List<User> users = [new(1, "Ada", new Address("London")), new(2, "Grace", null)];
foreach (var id in new[] { 1, 2, 3 })
{
Console.WriteLine($"{id}: {CityOf(users, id) ?? "unknown"}");
}
static string? CityOf(List<User> users, int id) => users.Find(user => user.Id == id)?.Address?.City;
record Address(string City);
record User(int Id, string Name, Address? Address);struct Address {
city: String,
}
struct User {
id: u32,
name: String,
address: Option<Address>,
}
fn city_of(users: &[User], id: u32) -> Option<&str> {
let user = users.iter().find(|user| user.id == id)?;
let address = user.address.as_ref()?;
Some(&address.city)
}
fn main() {
let users = vec![
User {
id: 1,
name: String::from("Ada"),
address: Some(Address {
city: String::from("London"),
}),
},
User {
id: 2,
name: String::from("Grace"),
address: None,
},
];
for id in [1, 2, 3] {
println!("{id}: {}", city_of(&users, id).unwrap_or("unknown"));
}
}Output
1: London 2: unknown 3: unknown
Each ? says: if this is None, return None from city_of right now; otherwise, give me the value inside. That’s a bigger jump than ?., which only ends one expression early. Rust’s ? ends the whole function, so it only works inside a function whose return type can carry the None: one that returns Option. (The next lesson covers ? on Result.) The last line wraps the answer back up with Some.
When you’d rather stay in one expression, Option has methods that do what ?. does:
fn city_of(users: &[User], id: u32) -> Option<&str> {
users
.iter()
.find(|user| user.id == id)
.and_then(|user| user.address.as_ref()) // the next step may be missing too
.map(|address| address.city.as_str()) // the next step is always there
}Output
London
The difference between the two is the shape of what the closure returns:
mapis for a step that always has a value, like?.citywhen every address has a city. The closure returns a plain value, andmapwraps it inSome.and_thenis for a step that might be missing too, like?.address. The closure returns anOption, andand_thenpasses it through. Withmap, you’d get anOption<Option<&Address>>.
Both do nothing when the value is already None, just like ?..
When missing is an error: ok_or
Sometimes “not found” shouldn’t be a quiet None; the caller needs a reason. ok_or and ok_or_else turn an Option into a Result, Rust’s type for “a value or an error”, which the next lesson covers:
fn name_of(users: &[User], id: u32) -> Result<&str, String> {
let user = users
.iter()
.find(|user| user.id == id)
.ok_or_else(|| format!("no user with id {id}"))?;
Ok(&user.name)
}
fn main() {
let users = vec![User {
id: 1,
name: String::from("Ada"),
}];
for id in [1, 9] {
match name_of(&users, id) {
Ok(name) => println!("{name}"),
Err(message) => println!("error: {message}"),
}
}
}Output
Ada error: no user with id 9
In TypeScript, you’d write if (user === undefined) throw new Error(...).The closest C# is FindUser(users, id) ?? throw new KeyNotFoundException(...). The difference is that the error is a value the function returns, and its type is in the signature.
To run different code for Some and None, rather than produce a value, use if let, let ... else or match from if let, while let & let-else. let Some(user) = find_user(&users, id) else { return; }; is Rust’s guard clause.
Which one should I use?
You’ll use a handful of these every day. Pick by what should happen when the value is missing:
| What | When | Why | How |
|---|---|---|---|
unwrap_or(value) | A cheap fallback: a number, a literal, a &str. | Rust’s ??. One expression, no branch to write. | settings.port.unwrap_or(8080) |
unwrap_or_else(|| ...) | A fallback that costs something: an allocation or a function call. | The closure runs only when the value is None. | name.unwrap_or_else(|| String::from("guest")) |
unwrap_or_default() | The type’s empty value is the right fallback. | 0, false, "", an empty Vec. | count.unwrap_or_default() |
? | You’re in a function that returns Option, and a missing value here means the result is missing too. | One flat line per step, like ?. but for the whole function. | let user = find_user(users, id)?; |
map(|v| ...) | Transform the value if it’s there, and keep the result optional. | Stays one expression; does nothing for None. | user.map(|user| user.id) |
and_then(|v| ...) | The next step can be missing too. | Avoids Option<Option<T>>. | user.and_then(|user| user.address.as_ref()) |
ok_or_else(|| ...)? | You’re in a function that returns Result, and a missing value is an error the caller should hear about. | Gives the caller a reason, not just None. | find_user(users, id).ok_or_else(|| format!("no user {id}"))? |
if let, let ... else, match | Each case runs different code. | The compiler checks you handled None. | let Some(user) = user else { return; }; |
as_ref(), as_deref() | You hold a &Option<T> (say, a field of a borrowed struct) and want to use the methods above. | Gives Option<&T> / Option<&str> without moving or copying the value. | settings.host.as_deref().unwrap_or("localhost") |
expect("why") | None would be a bug: you just checked, or the value is hard-coded. | Panics at this line with your message, instead of failing somewhere later. | args.first().expect("checked that args isn't empty") |
Option<&T> parameter | A function reads a value that may be missing. | Callers with a &T, a None or an Option<T> (via .as_ref()) can all call it. | See Choosing parameter types. |
Rule of thumb: inside a function that can give up, use ?. Where you need a real value, use unwrap_or (or unwrap_or_else if the fallback costs something). To transform the value and keep it optional, use map, or and_then when the next step can be missing. To run different code for each case, use let ... else or match. Use expect only where None would be a bug, and never as a translation of !.
The same choice as questions, asked in order:
Is there a sensible fallback value?
YesNounwrap_or(value)unwrap_or_else(|| ...)if the fallback costs something;unwrap_or_default()for 0, false or empty.Does the current function return
Option, and does a missing value here mean the result is missing too?YesNovalue?ReturnsNonefrom the whole function.Does the current function return
Result, and is a missing value an error the caller should hear about?YesNovalue.ok_or_else(|| error)?Do you want to transform the value and keep the result optional?
YesNomap(the next step always has a value) orand_then(it might not)Would
Nonehere mean a bug in your program, not a case to handle?YesNovalue.expect("why it can't be missing")It panics at this line with your message.Otherwise:
if let,let ... elseormatch: run different code for each case
Under the hood
Option is an ordinary enum, and its methods are ordinary functions. unwrap_or is a match:
fn unwrap_or<T>(option: Option<T>, default: T) -> T {
match option {
Some(value) => value,
None => default,
}
}
fn main() {
println!("{}", unwrap_or(Some(3), 8080));
println!("{}", unwrap_or(None, 8080));
}Output
3 8080
And value? in a function that returns Option is shorthand for match value { Some(v) => v, None => return None }. Once the compiler inlines them, a chain of map, and_then and ? becomes the same few branches you’d write by hand: no allocation, no closures left over.
What does the Option itself cost? It depends on whether the type inside has a value it never uses:
println!("i64: {}", size_of::<i64>());
println!("Option<i64>: {}", size_of::<Option<i64>>());
println!("&i64: {}", size_of::<&i64>());
println!("Option<&i64>: {}", size_of::<Option<&i64>>());
println!("String: {}", size_of::<String>());
println!("Option<String>: {}", size_of::<Option<String>>());Output
i64: 8 Option<i64>: 16 &i64: 8 Option<&i64>: 8 String: 24 Option<String>: 24
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
i64 | i648 bytes | 8 bytes | |||||||||||||||||||||||
Option<i64> | tag: Some or None (today)8 bytes | i648 bytes | 16 bytes | ||||||||||||||||||||||
&i64 | address8 bytes · pointer | 8 bytes | |||||||||||||||||||||||
Option<&i64> | address, or 0 for None8 bytes · pointer | 8 bytes | |||||||||||||||||||||||
String | pointer, capacity, length24 bytes | 24 bytes | |||||||||||||||||||||||
Option<String> | a String, or a value no String has for None24 bytes | 24 bytes | |||||||||||||||||||||||
Six values. An i64 is 8 bytes. Option<i64> is 16 bytes today, on a 64-bit target: a tag saying Some or None, then the 8-byte number, because every i64 bit pattern is a valid number. Today's compiler makes the tag 8 bytes wide to match the number's alignment; a 1-byte tag would leave 7 bytes of padding and take the same space. A reference, &i64, is an 8-byte address, and Option<&i64> is also 8 bytes, guaranteed: a reference is never 0, so None is stored as 0. A String is 24 bytes (pointer, capacity, length), and Option<String> is also 24 bytes today: None is stored as a value a String never holds, so no tag is needed.
Rust guarantees the Option<&T> row (and the same for Box<T>): an optional reference is exactly as big as a reference, with None stored as the null pointer that safe Rust never lets you see. The other sizes are what today’s compiler produces on a 64-bit target. The rule behind them: when the type inside has a bit pattern it never uses, None borrows it, and the Option costs nothing. A plain number uses every pattern, so its Option needs a tag.
undefined is just another value a variable can hold, so number | undefined has no layout to think about.C#‘s two kinds of T? show the same split. string? costs nothing, since a reference can already be null. long? is Nullable<long>, a struct that stores a HasValue flag next to the number, which also comes to 16 bytes:
Console.WriteLine(System.Runtime.CompilerServices.Unsafe.SizeOf<long?>());Output
16
Common pitfalls
Common pitfallunwrap_or runs its argument every time
The argument to unwrap_or is evaluated before the call, even when the value is Some and the fallback is thrown away:
fn default_name() -> String {
println!("building the default");
String::from("guest")
}
fn nickname() -> Option<String> {
Some(String::from("Ada"))
}
fn main() {
let name = nickname();
let eager = name.clone().unwrap_or(default_name()); // always calls default_name
let lazy = name.unwrap_or_else(default_name); // calls it only for None
println!("{eager} {lazy}");
}Output
building the default Ada Ada
When the fallback allocates or calls a function, use unwrap_or_else.
Common pitfallmap on a borrowed field tries to move it
map, unwrap_or and the others take the Option by value. On a field of a borrowed struct, that would move the value out, and the compiler stops you:
struct Settings {
host: Option<String>,
}
fn host_length(settings: &Settings) -> usize {
settings.host.map(|host| host.len()).unwrap_or(0)
}Rust doesn't compile this: error E0507
error[E0507]: cannot move out of `settings.host` which is behind a shared reference --> main.rs:6:5 | 6 | settings.host.map(|host| host.len()).unwrap_or(0) | ^^^^^^^^^^^^^ ---------------------- `settings.host` moved due to this method call | | | help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents | move occurs because `settings.host` has type `Option<String>`, which does not implement the `Copy` trait | note: `Option::<T>::map` takes ownership of the receiver `self`, which moves `settings.host` help: you can `clone` the value and consume it, but this might not be your desired behavior | 6 | <Option<String> as Clone>::clone(&settings.host).map(|host| host.len()).unwrap_or(0) | ++++++++++++++++++++++++++++++++++ + help: consider cloning the value if the performance cost is acceptable | 6 | settings.host.clone().map(|host| host.len()).unwrap_or(0) | ++++++++
Borrow the inside first: settings.host.as_ref().map(|host| host.len()), or settings.host.as_deref() for an Option<&str>. The compiler’s message suggests the same fix.
Common pitfallunwrap is not the ! operator
It’s tempting to translate every value! into value.unwrap(). They aren’t the same: ! tells the compiler to stop checking, while unwrap() checks at run time and panics if the value is None. So a missing value now stops the program, with a message pointing at the unwrap line. That’s better than a crash somewhere later, but it’s still a crash. Handle None with one of the methods above, and keep expect("why") for values that can’t be missing.
Try it yourself
Exercise: port this to Rust
Port this to Rust. managerName returns the name of an employee’s manager, or nothing if the employee doesn’t exist, has no manager, or the manager isn’t in the list. Write manager_name returning Option<&str>, with ? instead of the early returns.
type Employee = { id: number; name: string; managerId?: number };
function managerName(staff: Employee[], id: number): string | undefined {
const managerId = staff.find((employee) => employee.id === id)?.managerId;
if (managerId === undefined) return undefined;
return staff.find((employee) => employee.id === managerId)?.name;
}
const staff: Employee[] = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace", managerId: 1 },
{ id: 3, name: "Linus", managerId: 9 },
];
for (const id of [2, 1, 3, 4]) {
console.log(`${id}: ${managerName(staff, id) ?? "none"}`);
}List<Employee> staff = [new(1, "Ada", null), new(2, "Grace", 1), new(3, "Linus", 9)];
foreach (var id in new[] { 2, 1, 3, 4 })
{
Console.WriteLine($"{id}: {ManagerName(staff, id) ?? "none"}");
}
static string? ManagerName(List<Employee> staff, int id)
{
var managerId = staff.Find(employee => employee.Id == id)?.ManagerId;
if (managerId is null) return null;
return staff.Find(employee => employee.Id == managerId)?.Name;
}
record Employee(int Id, string Name, int? ManagerId);Expected output
2: Ada 1: none 3: none 4: none
Show a hint
Use ? three times in manager_name: after finding the employee, on its manager_id, and after finding the manager. In main, unwrap_or gives the fallback.
Show a solution
struct Employee {
id: u32,
name: String,
manager_id: Option<u32>,
}
fn manager_name(staff: &[Employee], id: u32) -> Option<&str> {
let employee = staff.iter().find(|employee| employee.id == id)?;
let manager_id = employee.manager_id?;
let manager = staff.iter().find(|employee| employee.id == manager_id)?;
Some(&manager.name)
}
fn main() {
let staff = vec![
Employee {
id: 1,
name: String::from("Ada"),
manager_id: None,
},
Employee {
id: 2,
name: String::from("Grace"),
manager_id: Some(1),
},
Employee {
id: 3,
name: String::from("Linus"),
manager_id: Some(9),
},
];
for id in [2, 1, 3, 4] {
println!("{id}: {}", manager_name(&staff, id).unwrap_or("none"));
}
}manager_name returns Option<&str>, so each ? hands None straight back to the caller: no such employee, no manager, or a manager id that matches nobody. manager_id is an Option<u32>, which is Copy, so ? can take it out of the borrowed employee without as_ref. main turns the None into text with unwrap_or.
Saved in this browser only.