1. There Is No null in Safe Rust References
How do you represent a missing value, or tell the caller an operation failed? A C pointer or a Java reference can be null. JavaScript has null and undefined for missing values.
Picture two identical delivery boxes, one of them empty. You run into trouble if you try to use the contents without checking which box you opened.
Even Tony Hoare, who invented the null reference, later called it his "billion-dollar mistake."1
Exceptions (throw / catch), which are common in other languages, come with a similar trap. When something goes wrong inside a function, an exception skips the normal return path and throws an emergency alarm upward.
If some caller catches that alarm, you get lucky, but if nobody catches it, your program abruptly crashes somewhere unexpected.
An even bigger issue is that looking at a function's signature (its name, parameters, and return type) often does not tell you whether it might throw an exception.
Developers end up reading documentation line by line and relying on memory to write defensive code.
Rust removes both problems head-on. Safe Rust references cannot be null, and recoverable failures are never thrown as exceptions.
Instead, they are returned as ordinary enum values, just like the ones you learned in Part 6.
When a value might or might not exist, you use Option<T>. When an operation can succeed or fail with a specific reason, you use Result<T, E>.
Absence and failure are no longer hidden landmines; they become plain data in front of you that the compiler checks every step of the way.2
2. Option<T>: A Safety Net for Popping an Empty Stack
Option<T>, built right into the standard library, is surprisingly simple. It has only two variants: Some(T) when a value is present, and None when it is empty.
The T inside the angle brackets is a generic type parameter, which acts like a blank slot that can hold any type.3
enum Option<T> {
Some(T),
None,
}Replace T with i32 and you get Option<i32>. The pair (&str, u32) gives you Option<(&str, u32)> instead. Picture an order that holds a name and a quantity for each item. We'll undo the most recent entry first.
A stack removes what you added last. Vec::pop() wraps that last entry in Some, or returns None if the list is empty. Add one item and pop twice to see both cases.
fn main() {
let mut items: Vec<(&str, u32)> = Vec::new();
items.push(("tea", 3));
for _ in 0..2 {
match items.pop() {
Some((item, quantity)) => println!("Removed: {} x{}", item, quantity),
None => println!("There are no items to remove."),
}
}
}Output:
Removed: tea x3
There are no items to remove.Vec::new() starts an empty, growable list. items.push(("tea", 3)) adds the pair, so the first pop() returns Some(("tea", 3)). The Some((item, quantity)) pattern binds one name to each part of that pair.
The _ in for _ in 0..2 means we don't use the loop counter. By the second trip through the loop the list is empty, so Rust runs the None arm. let (item, quantity) = items.pop(); would fail to compile because the return type is an Option, not a bare pair.
3. Result<T, E> and the ? Operator: Returning Failures as Values
Part 3 used read_line to read an order quantity and expect when parsing it. A blank line or abc stopped that program. Here we'll give a blank, an invalid number, zero, and an order over the limit distinct results so a caller can act on the reason.
Result<T, E> returns either Ok(T) with the value or Err(E) with the reason it failed. This program first reads a number from the text and then checks the quantity. Replace src/main.rs with the following code.
#[derive(Debug, PartialEq)]
enum OrderError {
EmptyQuantity,
InvalidQuantity,
ZeroQuantity,
TooManyItems { requested: u32, max: u32 },
}
fn parse_quantity(input: &str) -> Result<u32, OrderError> {
let text = input.trim();
if text.is_empty() {
return Err(OrderError::EmptyQuantity);
}
match text.parse::<u32>() {
Ok(quantity) => Ok(quantity),
Err(_) => Err(OrderError::InvalidQuantity),
}
}
fn validate_quantity(quantity: u32) -> Result<(), OrderError> {
const MAX: u32 = 100;
if quantity == 0 {
return Err(OrderError::ZeroQuantity);
}
if quantity > MAX {
return Err(OrderError::TooManyItems { requested: quantity, max: MAX });
}
Ok(())
}
fn prepare_order(input: &str) -> Result<u32, OrderError> {
let quantity = parse_quantity(input)?;
validate_quantity(quantity)?;
Ok(quantity)
}
fn main() {
println!("Enter the order quantity:");
let mut input = String::new();
match std::io::stdin().read_line(&mut input) {
Ok(_) => println!("{:?}", prepare_order(&input)),
Err(error) => eprintln!("Could not read the input: {}", error),
}
}Run cargo run --quiet and type 3. Its final line is Ok(3). Run the program again for each input on the left and compare its final line with the one on the right.
3 β Ok(3)
(blank) β Err(EmptyQuantity)
abc β Err(InvalidQuantity)
0 β Err(ZeroQuantity)
101 β Err(TooManyItems { requested: 101, max: 100 })#[derive(Debug, PartialEq)] on OrderError supplies {:?} formatting and equality with ==. TooManyItems carries both numbers the caller needs: the requested quantity and the maximum.
parse_quantity uses trim() to strip surrounding whitespace. If no text remains it returns EmptyQuantity. In parse::<u32>(), the ::<u32> tells Rust what type to parse. A value such as abc that can't be read as an unsigned 32-bit integer produces InvalidQuantity.
Once parsing succeeds, validate_quantity checks the range 1 through 100. It has no new number to return on success, so it returns Ok(()) with the unit value (). The previous step already supplied the quantity.
let quantity = parse_quantity(input)?; takes the quantity out of Ok. On an Err, prepare_order returns there, before the range check. validate_quantity(quantity)?; likewise returns early on an error, and reaching the final Ok(quantity) means both stages passed.4
On an Option, ? returns early for None. The enclosing function needs a return type capable of carrying that failure. This fn main() returns (), so it uses match to handle reading the line rather than propagating the error with ?.
The last println! uses {:?} to print the result's variant and fields. Try 101 to see requested: 101 next to max: 100.
Let's also mention the .unwrap() method that beginners often see in practice examples.
Use .unwrap() to take the value out of an Option or Result. It panics on None or Err, which stops a small program like this one if nothing handles the panic.
In a test where you expect success, .unwrap() can be handy. A terminal user can submit a blank line by pressing Enter, so handle that failure with match or pass it to the caller with ? instead.
When building real software, avoid leaning on .unwrap() and get into the habit of handling failures with match or forwarding them with ? so errors stay plain data all the way through.
Footnotes
- Tony Hoare, "Null References: The Billion Dollar Mistake", QCon London 2009. β©
- Rust Standard Library, std::result::Result: https://doc.rust-lang.org/std/result/enum.Result.html β©
- Rust Standard Library, std::option::Option: https://doc.rust-lang.org/std/option/enum.Option.html β©
- The Rust Programming Language, Ch. 9.2 Recoverable Errors with Result (? operator): https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html β©