Sub topic 1
Why Rust Has No Null and No Exceptions
Most languages let any value be null and let any function throw an exception. Rust does neither. It puts "this might be missing" and "this might fail" into the types of your functions. This chapter explains the reasoning and shows what it looks like in code. Later chapters cover the tools for working with these types.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: functions,
letbindings, and structs. - Enums and
matchexpressions. - Ownership and borrowing basics.
- Generics and traits at a conceptual level.
- Closures and iterators at a basic level.
You do not need to know any error-handling methods yet. The chapter introduces the two types by name and shows how they behave.
The problem with null
In many languages, a reference can point at nothing. The value is called null, nil, or None. Any variable of a reference type might hold it, and the type does not tell you which variables do. Calling a method on null fails at runtime, for example with a NullPointerException in Java. Tony Hoare, who introduced null references in 1965, later called it his "billion-dollar mistake".
The core issue is that the type system tells a small lie. A String in Java means "a string or null". The compiler cannot tell you which one you have, so every use carries a hidden question: did anyone check this?
The problem with exceptions
Exceptions have a similar flaw. A function signature like int parseInt(String s) says nothing about the failure case. The function may throw, and the compiler often does not make you handle it. Java's checked exceptions try to fix this, but most other languages do not. Three costs follow:
- Invisible control flow. Any call may jump out of the current function to a handler somewhere up the stack.
- Unclear contracts. To learn what can fail, you read documentation or source code, not the signature.
- Easy to forget. Nothing forces you to write the
catch, so the failure shows up in production.
Rust's answer: two ordinary enums
Rust removes both problems by moving them into the type system. The standard library defines two enums, which are in scope in every program:
Option<T>has the variantsSome(T)andNone. It means "aT, or nothing".Result<T, E>has the variantsOk(T)andErr(E). It means "aT, or an error of typeE".
They are plain enums with no special language support. You handle them with the same match you use for your own enums. Here is a lookup that can come back empty:
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<&str, u32> = HashMap::new();
stock.insert("apples", 3);
let apples = stock.get("apples");
let pears = stock.get("pears");
println!("{apples:?} {pears:?}");
}This prints Some(3) None. The method get does not return a bare u32. It returns Option<&u32>, so the "might be missing" fact is part of the signature. Here is the failure case:
fn main() {
println!("{:?}", "42".parse::<i32>());
println!("{:?}", "42x".parse::<i32>());
}The output is:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })The error is an ordinary return value. Nothing was thrown, and the caller receives it through the normal return path.
Absence versus failure
The two types answer different questions, so choosing between them is a design decision.
| Situation | Type | Example |
|---|---|---|
| A missing value is normal and needs no explanation | `Option<T>` | Looking up a key, finding the first match in a list |
| The operation failed and the caller may want to know why | `Result<T, E>` | Parsing text, reading a file, opening a connection |
A useful test is to ask whether the caller would want a reason. A HashMap lookup has only one way to come up empty, so None says everything. Parsing a number can fail because the text is empty, has a bad character, or overflows. Those are different reasons, so the error type carries them.
What the compiler forces on you
Option<i32> and i32 are different types. You cannot use one where the other is expected. If you write let m = n + 1; where n is an Option<i32>, the compiler rejects it with error[E0369]: cannot add {integer} to Option<i32>. To get at the inner value, you must say what happens in each case. That is exactly what the next chapters teach.
The effect is that the places where a value can be missing are marked in the types. If a variable is a plain String, it is a string. You never need to check it for null, because there is no way for it to be null. The checks you do write are concentrated where Option appears, and the compiler verifies you wrote them.
Result is also marked #[must_use]. If you call a function and ignore its Result, the compiler warns you:
fn main() {
"12".parse::<i32>();
println!("done");
}This compiles and prints done, but the compiler emits the warning unused Result that must be used. A failure cannot be dropped silently by accident.
No runtime cost for being explicit
You might expect wrapping every optional value to cost memory. For many types it does not. Rust uses the invalid bit patterns of a type to store None. A reference can never be null, so None can use the all-zero address. This is called the null pointer optimization.
use std::mem::size_of;
fn main() {
assert_eq!(size_of::<Option<&i32>>(), size_of::<&i32>());
assert_eq!(size_of::<Option<Box<i32>>>(), size_of::<Box<i32>>());
println!("Option adds no space for references and boxes");
}Both assertions hold, so the program prints its message. Types like Option<i32> do need extra space for the tag that says which variant is present. The guarantee is narrower: a reference or Box wrapped in Option is exactly as large as the bare one.
Panics: the third category
Rust does have a failure mechanism that unwinds the stack, called a panic. Indexing past the end of a vector, an integer divide by zero, and calling unwrap on a None all panic. A panic is not a replacement for exceptions. It is meant for bugs, where the program has reached a state its author believed was impossible. By default a panic prints a message and ends the thread. In a single-threaded program that ends the whole program.
Two details are worth knowing:
- Panics can technically be caught with
std::panic::catch_unwind, but this is for boundaries such as foreign-function interfaces and thread pools. It is not a way to handle expected errors. - A project can set
panic = "abort"in itsCargo.toml. The process then terminates immediately without unwinding. Code that relies on catching panics breaks under that setting.
The split between recoverable errors (Result) and bugs (panic) is deliberate, and a later chapter covers when each is right.
Deciding which one to use
The diagram summarizes the decision you make each time you write a function that might not produce a value.
Common mistakes
- Treating
Noneas an error without a reason. If callers will need to know why a value is missing,Optionthrows that information away. Return aResult. - Using
Resultwhen absence is normal. Makingget-style lookups returnErrforces callers to handle an error that is not one. - Expecting exceptions to exist somewhere. Code ported from Java or Python often tries to "throw" with
panic!. This makes ordinary failures crash the program. Return aResultinstead. - Ignoring a
Resultwarning. Theunused Resultwarning means an error path is being dropped. Treat it as a bug.
Exercise
Exercise
A function find_user(id: u32) searches an in-memory list and returns the matching user, or nothing if the id is unknown. A second function load_user(id: u32) reads the user from a database that can be unreachable, time out, or return corrupt data. Which return type fits each function, and why?
Show answer
find_user should return Option<User>. Not finding a user is a normal outcome with one possible cause, so None is enough. load_user should return Result<User, E>, where E describes the failure. The caller needs to tell an unreachable database from a timeout or corrupt data, and Option would discard that reason. A panic would be wrong for both, because neither case is a bug in the program.
Exercise
Why can Option<&i32> be the same size as &i32, while Option<i32> is larger than i32?
Show answer
A reference is never null, so Rust can store None as the all-zero address without any extra space. Every bit pattern of an i32 is a valid number, so there is no spare pattern to mean None. Option<i32> needs an extra tag to record which variant it holds.