Sub topic 1
Why Rust has no null and no exceptions
Prerequisites
This chapter assumes you know basic Rust syntax (functions, let bindings, structs), enums and match, ownership and borrowing basics, and generics and traits at a conceptual level. You should also be comfortable with simple closures and iterators.
Two problems, two kinds of value
Most programs have to deal with two situations:
- Absence. A value might not exist. A search finds nothing, a map has no entry for a key, a config file leaves a setting blank.
- Failure. An operation might not succeed. A string is not a number, a file cannot be opened, a network call times out.
Many languages handle both with hidden mechanisms. Absence becomes null, and failure becomes an exception that jumps up the call stack. Neither shows up in a function's signature, so the compiler cannot tell you when you forgot to handle them.
Rust has neither mechanism. It uses ordinary enum values instead:
| Situation | Rust type | Variants |
|---|---|---|
| A value may be missing | `Option<T>` | `Some(T)` or `None` |
| An operation may fail | `Result<T, E>` | `Ok(T)` or `Err(E)` |
What goes wrong with null
With null, any reference can be a valid value or a missing one, and the type does not say which. Forgetting a check leads to a crash at runtime, often far from the cause. In Rust, a plain i32 or &str is never missing. If a value can be missing, the type is Option<i32> or Option<&str>, and you cannot use the inner value until you have dealt with None.
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
match first_even(&[1, 3, 4, 5]) {
Some(n) => println!("found {n}"),
None => println!("no even number"),
}
}The signature tells every caller that an even number might not exist. The match must cover both variants, or the code does not compile.
What goes wrong with exceptions
An exception can be thrown by any call, and nothing in the signature warns you. Control flow jumps out of the function, skipping the code after the call. In Rust, a recoverable failure is an Err value returned like any other value, so the possibility of failure is part of the function's type.
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
}This prints Ok(8080) and then Err(ParseIntError { kind: InvalidDigit }). The bad input did not throw anything. It produced a value that the caller can inspect, transform, or pass along.
What this costs and what it buys
The cost is some extra code at each call site. You write match, ?, or a combinator where another language would let the problem slide.
What you get in return:
- The compiler checks that you handled every case.
- Signatures document what can go wrong.
- Control flow is visible. There are no hidden jumps.
Rust does have a separate mechanism, the panic, for bugs and unrecoverable states. Later chapters cover when to use it.
Exercise
A function needs to look up a user's age by name, and the user might not exist. Which return type fits, Option<u32> or Result<u32, E>, and why?
Show answer
Option<u32> fits if "not found" is a normal outcome with nothing more to report. Use Result<u32, E> if the lookup can fail for reasons the caller needs to tell apart, such as a database error. In both cases the signature tells the caller that a value may not come back.