A customer asks the price of coffee, but coffee just isn't on the menu at Rusdi's Pancake Stall. Nothing went wrong: the answer is simply "there isn't any". An order form whose portion box says "two" in letters is different. The cashier can't read it as a number, so the order can't be taken, and the cashier has to explain why: "the portion isn't a number".
Rust keeps these two cases firmly apart. Many other languages use null (a sign for "no value") and exceptions (errors that stop the code and are caught somewhere else). Rust has neither. Instead it has two built-in enums: Option<T> for a value that might not be there, and Result<T, E> for work that can fail, together with the reason why. T is the type of the value when it is there or the work succeeds, and E is the type of the reason when it fails. The answer "yes, it's 5" or "there isn't any" is an Option: Some(5) or None. The answer "done, 2 portions" or "failed, because ..." is a Result: Ok(2) or Err(reason).
Option: maybe there, maybe not
The function price below is the same as in the enum lesson, now with iced orange. Then main tries several ways of reading its result:
fn price(menu: &str) -> Option<u32> {
match menu {
"sweet pancake" => Some(32),
"egg pancake" => Some(38),
"iced tea" | "iced orange" => Some(5),
_ => None,
}
}
fn main() {
let tea = price("iced tea");
let coffee = price("coffee");
println!("{:?} {:?}", tea, coffee);
match coffee {
Some(h) => println!("Coffee {}", h),
None => println!("Coffee is not on the menu"),
}
if let Some(h) = tea {
println!("Iced tea {}", h);
}
println!("{}", coffee.unwrap_or(0));
println!("{:?}", tea.map(|h| h * 3));
println!("{} {}", tea.is_some(), coffee.is_none());
}
Some(5) None
Coffee is not on the menu
Iced tea 5
0
Some(15)
true true
matchmust handle bothSomeandNone. The compiler won't let you forget the "not there" case.if let Some(h) = tea { ... }runs its block only whenteaholds aSome, and puts the value inside thatSomeintoh. It is like amatchwith just one arm. IfteaisNone, the block is skipped without any message.- The opposite is
let ... else: onNone, the code leaves early, and onSome, the value inside, herep, can be used in the lines after it. For example, infn total(menu: &str, portions: u32) -> u32, the linelet Some(p) = price(menu) else { return 0; };is followed byp * portions. As a result,total("iced tea", 2)gives 10 andtotal("coffee", 2)gives 0. Theelseblock must leave (return,break, or a panic). If it doesn't, the compiler refuses:`else` clause of `let...else` does not diverge. unwrap_or(0)gives the value inside when it'sSome, or the fallback value (the default) 0 when it'sNone.coffeeisNone, so 0 is printed.map(|h| h * 3)uses a closure to change the value inside aSome(5 becomes 15). ANonestaysNone.is_some()givestruewhen the value is aSome, andis_none()givestruewhen it isNone.- An
Option<u32>is not au32.price("iced tea") == 5is refused withexpected `Option<u32>`, found integer, and the compiler suggestsSome(5).
Result: success, or failure with a reason
parse turns text into a number, and it can fail. This program tries four entries in the portion box:
fn main() {
let entries = ["2", "two", "", "5000000000"];
for text in entries {
let portions: Result<u32, _> = text.parse::<u32>();
println!("{:?}", portions);
match portions {
Ok(n) => println!("{} portions", n),
Err(e) => println!("Failed: {}", e),
}
}
}
Ok(2)
2 portions
Err(ParseIntError { kind: InvalidDigit })
Failed: invalid digit found in string
Err(ParseIntError { kind: Empty })
Failed: cannot parse integer from empty string
Err(ParseIntError { kind: PosOverflow })
Failed: number too large to fit in target type
text.parse::<u32>()turnstextinto au32:::<u32>names the target type. The result is aResult<u32, ParseIntError>:Ok(number)when it works, orErr(error)when it fails.ParseIntErroris the error type for text that can't be read as a number. The_inResult<u32, _>means "fill in the type yourself", and the compiler fills inParseIntError.- The error carries the reason.
{:?}shows it for programmers,ParseIntError { kind: InvalidDigit }.{}shows it for customers,invalid digit found in string. "5000000000"fails because au32is at most 4,294,967,295.parseneeds to know its target type.let portions = "2".parse().unwrap();is refused with E0284type annotations needed. Writeparse::<u32>()orlet portions: u32.
Option or Result?
Use Option when "not there" is normal and needs no explanation: looking up a price on the menu, orders.get(3), HashMap::get. Use Result when the work can fail and the caller should know why: reading a number from text, opening a file, calling a server. Each can be turned into the other: .ok_or(reason) turns an Option into a Result by adding a reason, and .ok() turns a Result into an Option by dropping the reason.
A function that uses both usually returns a Result, because its failures need explaining. The function total below looks up the price, then reads the portions:
fn total(menu: &str, portions: &str) -> Result<u32, String> {
let h = match price(menu) {
Some(h) => h,
None => return Err(format!("{} is not on the menu", menu)),
};
match portions.parse::<u32>() {
Ok(p) => Ok(h * p),
Err(e) => Err(format!("portions \"{}\": {}", portions, e)),
}
}
The arm None => return Err(...) leaves the function right away with an error, so h gets a value only when the price exists. \" is a quote mark inside a text. total("egg pancake", "2") gives Ok(76), total("coffee", "2") gives Err("coffee is not on the menu"), and total("iced tea", "two") gives Err("portions \"two\": invalid digit found in string"). The step "if it fails, give the error straight back to the caller" is so common that Rust has a short way to write it, the ? operator. That's the next lesson.
Working without match
This program works on Option and Result values with methods, without match. menu is an array of four menu names:
fn main() {
let menu = ["sweet pancake", "egg pancake", "iced tea", "coffee"];
println!("{:?}", menu.get(2).and_then(|m| price(m)));
println!("{:?}", menu.get(3).and_then(|m| price(m)));
println!("{:?}", menu.get(9).and_then(|m| price(m)));
println!("{:?}", price("coffee").ok_or("coffee is not on the menu"));
println!("{:?}", price("iced tea").ok_or("iced tea is not on the menu"));
let portions = "two".parse::<u32>().unwrap_or(1);
println!("{}", portions);
println!("{:?}", "2".parse::<u32>().ok());
}
Some(5)
None
None
Err("coffee is not on the menu")
Ok(5)
1
Some(2)
and_thenjoins two steps that can each giveNone: from a menu number to a name (menu.get(2)), then from the name to a price (price(m)). Number 2 is iced tea, so the result isSome(5). Number 3 exists, but coffee has no price. Number 9 doesn't exist at all. So both of those giveNone. The difference frommap: the closure inmapreturns a plain value, andmapwraps it inSome. The closure inand_thenalready returns anOption, andand_thenuses thatOptionas it is, so the result doesn't becomeSome(Some(...)).ok_or("...")adds a reason:NonebecomesErr("coffee is not on the menu"), andSome(5)becomesOk(5).unwrap_or(1)on aResultgives the fallback value 1 when it fails. Careful: "two" quietly becomes 1 portion, when the customer wanted two. A fallback value is only safe when it truly makes sense..ok()drops the reason:Ok(2)becomesSome(2).
The methods map and and_then exist on Result too: map changes the value in Ok, and and_then joins steps that can fail.
unwrap and expect
You have used unwrap() since the data types lesson, to take the number out of .parse(). This program uses the price above, then takes the value out with unwrap(): once for iced tea, once for coffee. Before you look at the output, guess: what happens?
fn main() {
println!("Iced tea: {}", price("iced tea").unwrap());
let coffee = price("coffee").unwrap();
println!("Coffee: {}", coffee);
}
Iced tea: 5
thread 'main' (25517591) panicked at src/main.rs:12:34:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The code compiles. Iced tea: 5 is printed, then the program panics (stops immediately) at the second unwrap(). unwrap() means "I'm sure there's a value". On Some(42), unwrap() gives 42, and on Ok(2) it gives 2. But on None or Err, unwrap() stops the program. The Coffee: line is never printed, and cargo run exits with code 101, the sign that the program stopped because it failed. The number in brackets after 'main' is the thread's number, and it is different on every run.
expect works like unwrap, but you write the panic message yourself:
fn main() {
let portions: u32 = "two".parse().expect("portions must be a number");
println!("{}", portions);
}
thread 'main' (25518653) panicked at src/main.rs:2:39:
portions must be a number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Your message is printed first, then the reason from the Err.
Why is unwrap in production code (code that real users run) considered a warning sign? Imagine a cashier app that crashes for everyone just because one customer mistyped a portion. unwrap is fine in small examples, in tests and in prototypes (trial versions). In production code, handle None and Err with match, if let or the methods above. When you're truly sure something can't fail, use expect with a message explaining why. Then, if you are wrong, the message points straight at the problem.
panic or Result?
Panic is for bugs: an assumption in your own program that turned out wrong, such as an index out of bounds, or data that "must be there" and isn't. The program stops, because continuing with wrong data is more dangerous. Result is for failures that normally come from outside the program: user input, a missing file, a lost network connection. How to choose: if this work fails, can the caller do something sensible? If so, return a Result.
⚠️ Shortcuts that crash, or go quietly wrong
unwrap()everywhere. The code compiles, then panics when the input is not what you expected. HandleNoneandErr, or useexpectwith a reason.- Treating an
Option<u32>like au32.price("iced tea") == 5is refused (E0308), and so isprice("iced tea") + 2(E0369cannot add `{integer}` to `Option<u32>`). Take the value out first. parse()with no target type. E0284type annotations needed. Writeparse::<u32>().- A default that hides the problem.
unwrap_or(0)makes coffee free andunwrap_or(1)makes "two" one portion. Pick a fallback value that truly makes sense, or report the error.
TL;DR: Option<T> is Some(value) or None, for a value that might not be there, such as the price of something that isn't on the menu (price("coffee")). Result<T, E> is Ok(value) or Err(reason), for work that can fail. For example, "two".parse::<u32>() (which turns text into a u32 number) gives Err(ParseIntError { kind: InvalidDigit }), which {} prints as invalid digit found in string. Handle both with match or if let (a match with one arm). You can also work on them with methods: unwrap_or (the value, or a fallback value), map (changes the value), and_then (joins steps that can fail), ok_or (Option to Result) and ok (Result to Option). unwrap() gives the value (Some(42).unwrap() is 42) but panics (stops the program) on None or Err. expect("...") does the same with your own message. Panic is for bugs, Result for failures that normally come from outside the program.
⚡ Option: maybe there, maybe not
Write:
match price("coffee") {
Some(h) => println!("Coffee {}", h),
None => println!("Coffee is not on the menu"),
}
Meaning: price looks up the price of a menu item. The result is an Option: a Some with the price inside when the item is on the menu, or None when it isn't. Coffee isn't on the menu, and that's normal, so no reason is needed. match must handle both Some and None.
⚡ Result: failure, plus the reason
Write:
match "two".parse::<u32>() {
Ok(n) => println!("{} portions", n),
Err(e) => println!("Failed: {}", e),
}
Meaning: parse::<u32>() turns text into a u32 number, and it can fail. The result is a Result: Ok(value) when it works, or Err(reason) when it fails. "two" is written in letters, so the result is Err, and e holds the reason, printed as Failed: invalid digit found in string.
⚡ unwrap that panics
Guess first: unwrap() takes the value out of an Option. Iced tea is on the menu, coffee isn't. The program prints price("iced tea").unwrap(), then price("coffee").unwrap(). What happens?
The price of iced tea is printed, Iced tea: 5. Then the program panics (stops immediately) at the second unwrap(), because price("coffee") is None: called `Option::unwrap()` on a `None` value.
Meaning: unwrap() takes the value out of a Some or an Ok, and it means "I'm sure there's a value". On None or Err, unwrap() stops the program. In real code, handle None and Err with match, or use expect: like unwrap, but with a panic message you write yourself, giving a clear reason.