The Analogy: The Returned Parcel
A courier who takes a parcel out for delivery comes back with one of exactly two things in their hand. A signed receipt, or the parcel itself with a sticker on it. Never a shrug, never an empty hand, never "it's probably fine, I left it somewhere". That is Result<T, E>: Ok(T) is the receipt, carrying the thing you actually wanted, and Err(E) is the parcel coming back with an explanation attached.
The sticker is the whole point, and it is the entire difference between Result and Option. "No delivery" tells the depot nothing it can act on. A sticker reading nobody home, second attempt tomorrow leads to one action; address does not exist leads to a completely different one; recipient refused leads to a third. Option says there may be nothing here. Result says this may have failed, and here is which failure it was.
Both outcomes come back through the same slot. The receipt and the returned parcel land in the same tray on the same desk, and the clerk cannot file either one without first looking to see which it is. There is no route through the depot where you take the tray and act on its contents without opening it. That is why Result is a single enum rather than two separate outputs, and why the compiler will not let you touch the value inside until you have established which arm you are in.
Finally, somebody has to decide what stickers exist. A depot whose only stamp reads FAILED is technically returning information and practically useless. Rust does not choose the vocabulary for you -- the E in Result<T, E> is yours, and it can be a string, an enum of the four things that genuinely go wrong in your domain, or a rich structured type carrying the offending values. That choice outlives the code that made it, because every caller you will ever have has to match on it.
Syntax or Core Structure
Result is not special syntax. It is an ordinary enum with two generic parameters, defined in the standard library and available everywhere without an import:
enum Result<T, E> {
Ok(T),
Err(E),
}
Result, Ok and Err are all in the prelude, which is why -- unlike almost every other enum -- you write Ok(7) rather than Result::Ok(7).
fn main() {
let good: Result<i32, String> = Ok(7);
let bad: Result<i32, String> = Err(String::from("no digits"));
println!("good {good:?}");
println!("bad {bad:?}");
println!("good is_ok {}", good.is_ok());
println!("bad is_ok {}", bad.is_ok());
match good {
Ok(n) => println!("got {n}"),
Err(e) => println!("failed: {e}"),
}
match bad {
Ok(n) => println!("got {n}"),
Err(e) => println!("failed: {e}"),
}
}
Output:
good Ok(7)
bad Err("no digits")
good is_ok true
bad is_ok false
got 7
failed: no digits
More usefully, a function that returns one:
fn half(n: u32) -> Result<u32, String> {
if n % 2 == 0 {
Ok(n / 2)
} else {
Err(format!("{n} is odd"))
}
}
fn main() {
println!("{:?}", half(10));
println!("{:?}", half(7));
}
Output:
Ok(5)
Err("7 is odd")
Note what the signature already tells a reader before they look at the body: this can fail, the failure comes back as a String, and you will have to deal with it. None of that is a comment that can go stale.
Technical Depth: Result Against Option
You have both tools now, and choosing between them is a design decision you will make constantly.
Option<T> | Result<T, E> | |
|---|---|---|
| Variants | Some(T) / None | Ok(T) / Err(E) |
| The bad case carries | nothing | a value you designed |
| Reads as | "there may be no value" | "this may have failed, and here is why" |
| Warns when ignored | no | yes |
| Convert to the other | ok_or(e) / ok_or_else(f) | .ok() / .err() |
| Right when | absence is a normal, self-explanatory state | absence needs explaining before anyone can act |
HashMap::get returns Option because a missing key explains itself. fs::read_to_string returns Result because "no file" and "no permission" and "it is a directory" require completely different responses from the caller.
The Compiler Nags About Ignored Results
Result carries #[must_use], which makes throwing one away a warning rather than silent.
fn save(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err(String::from("empty name"));
}
println!("saved {name}");
Ok(())
}
fn main() {
save("ada");
save("");
println!("done");
}
Output (trimmed; rustc also prints a help: suggesting let _ = ..., and repeats the warning for line 12):
warning: unused `Result` that must be used
--> src/main.rs:11:5
|
11 | save("ada");
| ^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
Program output:
saved ada
done
That is the failure this lint exists to prevent. save("") failed, said so, and the program printed done as though nothing had happened. Note that it is a warning, which means it scrolls past in a build log; #![deny(unused_must_use)] at the crate root turns it into an error, and many teams do.
Handled instead:
fn main() {
match save("ada") {
Ok(()) => println!("ok"),
Err(e) => println!("error: {e}"),
}
match save("") {
Ok(()) => println!("ok"),
Err(e) => println!("error: {e}"),
}
}
Output:
saved ada
ok
error: empty name
Result<(), E> is the shape for an operation that either works or explains itself but has nothing to hand back. Ok(()) looks odd the first few times -- it is the Ok variant carrying the unit value -- and then it becomes invisible. Roughly half the Results in a real codebase look like this.
Where Results Come From
You will meet far more Results than you write, because the standard library returns one from every operation that touches the outside world or converts between types that do not always fit.
| Call | Returns |
|---|---|
"42".parse::<i32>() | Result<i32, ParseIntError> |
fs::read_to_string(path) | Result<String, io::Error> |
fs::write(path, data) | Result<(), io::Error> |
String::from_utf8(bytes) | Result<String, FromUtf8Error> |
u8::try_from(300_u32) | Result<u8, TryFromIntError> |
TcpStream::connect(addr) | Result<TcpStream, io::Error> |
writeln!(file, "...") | Result<(), io::Error> |
handle.join() on a thread | Result<T, Box<dyn Any + Send + 'static>> |
You will also see io::Result<T>, fmt::Result and friends around the standard library. Those are type aliases with the error already filled in -- io::Result<T> is literally Result<T, io::Error> -- and they exist to stop every signature in a module repeating the same error type.
parse is the easiest one to experiment with, and its errors are worth seeing:
fn main() {
let inputs = ["42", "-7", "0", "3.5", "", " 8", "999999999999"];
for s in inputs {
match s.parse::<i32>() {
Ok(n) => println!("{:<14} ok {n}", format!("{s:?}")),
Err(e) => println!("{:<14} err {e}", format!("{s:?}")),
}
}
}
Output:
"42" ok 42
"-7" ok -7
"0" ok 0
"3.5" err invalid digit found in string
"" err cannot parse integer from empty string
" 8" err invalid digit found in string
"999999999999" err number too large to fit in target type
Four things fall out of that table. parse does not trim, so leading whitespace is an invalid digit. It does not accept a decimal point when the target is an integer -- the . is just another invalid digit. It distinguishes empty input from bad input, which is genuinely useful. And it distinguishes too large from not a number, which means a caller can offer "that number is too big for this field" rather than "that is not a number". Feeding it a very negative value gives the matching number too small to fit in target type.
The type annotation is doing real work here. s.parse() on its own cannot compile, because parse is generic over what you want and nothing in the expression says which type. parse::<i32>() says it at the call site. Annotating the binding also works, but remember what the binding actually holds -- let n: Result<i32, _> = s.parse(); is right and let n: i32 = s.parse(); is a type error, because parse hands back the whole envelope, not its contents.
Reaching Inside Without Matching
A full match is the honest default and the next lesson is entirely about it. But for one-step transformations there is a set of methods that keep the code flat.
| Method | On Ok(v) | On Err(e) |
|---|---|---|
map(f) | Ok(f(v)) | unchanged |
map_err(f) | unchanged | Err(f(e)) |
and_then(f) | f(v), which is itself a Result | unchanged |
or_else(f) | unchanged | f(e), which is itself a Result |
unwrap_or(d) | v | d |
unwrap_or_else(f) | v | f(e) |
unwrap_or_default() | v | T::default() |
ok() | Some(v) | None, and the error is discarded |
err() | None | Some(e) |
as_ref() | Ok(&v) | Err(&e) |
fn main() {
let raw = ["10", "x", "30"];
let mut total = 0;
for s in raw {
let n = s.parse::<i32>().unwrap_or(0);
total += n;
println!("{s:>3} -> {n}");
}
println!("total {total}");
let doubled = "21".parse::<i32>().map(|n| n * 2);
println!("doubled {doubled:?}");
let relabelled = "x".parse::<i32>().map_err(|_| "not a number");
println!("relabelled {relabelled:?}");
let discarded = "x".parse::<i32>().ok();
println!("discarded {discarded:?}");
}
Output:
10 -> 10
x -> 0
30 -> 30
total 40
doubled Ok(42)
relabelled Err("not a number")
discarded None
Those |n| n * 2 arguments are closures, covered properly in Module 7; read them for now as small unnamed functions.
Two of these lines hide a decision. unwrap_or(0) turned "x is not a number" into a silent zero that got added to the total -- defensible for a demo, indefensible for a bank. And .ok() threw the reason away entirely, converting a Result into an Option and with it a why into a nothing. Both are legitimate tools and both are how error information leaks out of programs; use them where you have decided the reason does not matter, not where you have not yet decided.
as_ref() is the one that saves you from a borrow-checker fight. result.map(f) consumes the Result; result.as_ref().map(f) borrows it, so you can inspect it and still have it afterwards.
Designing The E
Result<T, String> is fine for a script and poor for anything a caller has to react to, because the only thing a caller can do with a String is print it. An enum lets them branch.
#[derive(Debug)]
enum SlotError {
Empty,
NotANumber,
OutOfRange { got: u32, max: u32 },
}
fn slot(text: &str) -> Result<u32, SlotError> {
if text.is_empty() {
return Err(SlotError::Empty);
}
let n = match text.parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(SlotError::NotANumber),
};
if n > 24 {
Err(SlotError::OutOfRange { got: n, max: 24 })
} else {
Ok(n)
}
}
fn main() {
println!("raw: {:?}", slot("99"));
println!();
for s in ["9", "", "noon", "99"] {
match slot(s) {
Ok(n) => println!("{:<6} hour {n}", format!("{s:?}")),
Err(SlotError::Empty) => println!("{:<6} needs an hour", format!("{s:?}")),
Err(SlotError::NotANumber) => println!("{:<6} not a number", format!("{s:?}")),
Err(SlotError::OutOfRange { got, max }) => {
println!("{:<6} {got} is past {max}", format!("{s:?}"))
}
}
}
}
Output:
raw: Err(OutOfRange { got: 99, max: 24 })
"9" hour 9
"" needs an hour
"noon" not a number
"99" 99 is past 24
Three variants, three different messages, and one of them quoting the numbers that caused the problem. That last part is the difference between an error type and a category label: OutOfRange alone would tell the caller which rule was broken, and OutOfRange { got, max } tells them enough to write the sentence a user needs to read.
#[derive(Debug)] is the minimum for an error type -- without it you cannot print it at all, and unwrap will not compile. A type you intend other people to use also wants Display (so it prints without the braces) and std::error::Error (so it slots into the ecosystem's machinery). Both are trait implementations, which is Module 6.
main Can Return One Too
fn main() -> Result<(), String> {
let text = "21";
match text.parse::<i32>() {
Ok(n) => {
println!("{}", n * 2);
Ok(())
}
Err(e) => Err(format!("bad input: {e}")),
}
}
Output:
42
Change text to "x" and the program prints nothing to standard output and this to standard error:
Error: "bad input: invalid digit found in string"
The runtime accepts Result<(), E> from main for any E that implements Debug. On Err it prints Error: followed by the Debug form -- which is why the string arrives with quotes around it -- and exits with status 1. Not 101: this is a return, not a panic, so nothing unwound and nothing crashed. That distinction is exactly the one from the previous lesson, now visible in the exit code.
Real World Example: Reading Settings Lines
A key = value config file is where error design earns its keep, because there are five genuinely different ways a line can be wrong and a user staring at the output needs to know which one they hit.
#[derive(Debug)]
enum ConfigError {
NoEquals,
EmptyKey,
UnknownKey(String),
BadNumber { key: String, value: String },
TooLarge { key: String, value: u32, max: u32 },
}
struct Settings {
port: u32,
workers: u32,
name: String,
}
fn number(key: &str, value: &str, max: u32) -> Result<u32, ConfigError> {
let n = match value.parse::<u32>() {
Ok(n) => n,
Err(_) => {
return Err(ConfigError::BadNumber {
key: key.to_string(),
value: value.to_string(),
})
}
};
if n > max {
Err(ConfigError::TooLarge {
key: key.to_string(),
value: n,
max,
})
} else {
Ok(n)
}
}
fn apply(settings: &mut Settings, line: &str) -> Result<(), ConfigError> {
let eq = match line.find('=') {
Some(i) => i,
None => return Err(ConfigError::NoEquals),
};
let key = line[..eq].trim();
let value = line[eq + 1..].trim();
if key.is_empty() {
return Err(ConfigError::EmptyKey);
}
match key {
"port" => match number(key, value, 65535) {
Ok(n) => {
settings.port = n;
Ok(())
}
Err(e) => Err(e),
},
"workers" => match number(key, value, 64) {
Ok(n) => {
settings.workers = n;
Ok(())
}
Err(e) => Err(e),
},
"name" => {
settings.name = value.to_string();
Ok(())
}
_ => Err(ConfigError::UnknownKey(key.to_string())),
}
}
fn explain(e: &ConfigError) -> String {
match e {
ConfigError::NoEquals => String::from("no '=' in the line"),
ConfigError::EmptyKey => String::from("nothing before the '='"),
ConfigError::UnknownKey(k) => format!("unknown key {k:?}"),
ConfigError::BadNumber { key, value } => {
format!("{key} needs a number, got {value:?}")
}
ConfigError::TooLarge { key, value, max } => {
format!("{key} is {value}, limit is {max}")
}
}
}
And the driver:
fn main() {
let lines = [
"port = 8080",
"workers=4",
"name = edge-1",
"port 9000",
" = 3",
"timeout = 30",
"workers = many",
"port = 70000",
];
let mut settings = Settings {
port: 80,
workers: 1,
name: String::from("unnamed"),
};
let mut applied = 0;
let mut rejected = 0;
for line in lines {
match apply(&mut settings, line) {
Ok(()) => {
applied += 1;
println!("ok {line:?}");
}
Err(e) => {
rejected += 1;
println!("error {line:?}");
println!(" {}", explain(&e));
}
}
}
println!();
println!("{applied} applied, {rejected} rejected");
println!(
"port {}, workers {}, name {:?}",
settings.port, settings.workers, settings.name
);
}
Output:
ok "port = 8080"
ok "workers=4"
ok "name = edge-1"
error "port 9000"
no '=' in the line
error " = 3"
nothing before the '='
error "timeout = 30"
unknown key "timeout"
error "workers = many"
workers needs a number, got "many"
error "port = 70000"
port is 70000, limit is 65535
3 applied, 5 rejected
port 8080, workers 4, name "edge-1"
Every rejected line gets a sentence that names the specific thing that went wrong, and three of those sentences quote values that only the error value could have carried. Had apply returned bool, or Option<()>, the loop could report "line 6 was bad" and stop there. The E parameter is where a library's usefulness lives: it is the difference between telling a user their config is broken and telling them that port is 70000 and the limit is 65535.
Now look at the "port" arm and notice how much of it is ceremony. Seven lines to say "parse it, store it, or pass the error along" -- and the Err(e) => Err(e) arm does nothing at all except take the error out of one envelope and put it into an identical one. That shape repeats in the "workers" arm and would repeat in every arm of a real config parser. This is not a flaw in Result; it is the reason the rest of this module exists. The ? operator collapses each of those blocks into a single line, and this program is the before picture.
Two details worth pointing at. find('=') returns a byte offset, so line[..eq] and line[eq + 1..] are byte slices -- normally a boundary hazard, and here provably safe, because = is a one-byte character: eq is the start of a character and eq + 1 is the start of the next, whatever else the line contains. And ConfigError calls to_string() on everything it carries, which costs an allocation per rejected line and buys an error value that owns its data and can therefore outlive the buffer it came from -- you can log it, return it up several layers, or store it. An error type that borrowed from line would be free and would tie every caller, forever, to the lifetime of the input.
The honest limits. Comments and blank lines are not handled at all: a # line reports as an unknown key and a blank line reports as a missing =, both technically true and both useless. Duplicate keys silently overwrite, so port = 8080 followed by port = 3000 leaves 3000 and reports two successes with no hint that they disagreed. Errors are per line and processing continues, which is right for a config file but leaves settings half-applied -- there is no transaction, and a caller who does not count cannot distinguish "all eight lines applied" from "three did". The line number is not in the error, which is why the loop had to print the raw line itself; that works only because the caller happens to be the loop that has it. And the limits 65535 and 64 are bare literals at two call sites, which is where a limit goes to get out of sync with the documentation.
Common Mistakes
- Ignoring the result and reading the warning as noise.
#[must_use]fires, the build log scrolls, and a failed write becomes a file that quietly does not exist. Turn it into an error with#![deny(unused_must_use)]if your team lets warnings accumulate.
- Silencing it with
let _ =instead of deciding. That is a legitimate way to say "I have considered this failure and I genuinely do not care", and an illegitimate way to make a warning go away. The two look identical in the diff, which is why the first deserves a comment.
- Calling
.ok()early. It convertsResulttoOptionby deleting the error, and it usually happens three layers below the code that needed to know why. If you are about to write.ok(), check whether you are discarding the only explanation anyone will ever get.
Result<T, String>in a public API. Callers cannot branch on prose. They will end up matching on substrings of your messages, and then your next wording improvement is a breaking change.
- Forgetting the trailing
Ok(()). A function returningResult<(), E>whose happy path just does work will not compile without it, and the error message about mismatched types is confusing the first time because nothing looks like it is returning anything.
unwrap_or_elseandunwrap_orused interchangeably.unwrap_or(expensive())evaluatesexpensive()every time, including on success.unwrap_or_else(|_| expensive())evaluates it only on failure. Same shape, different cost.
map_err(|_| "failed"). This is a category error dressed as a conversion: it throws away everything the original error knew and replaces it with a word. Keep the original around, even if only in a variant that wraps it.
- Confusing
Option<Result<T, E>>withResult<Option<T>, E>. The first is "maybe there was an attempt, and it may have failed". The second is "the attempt happened and may have produced nothing". They are different questions and the compiler will not tell you that you asked the wrong one.
- Error enums that borrow from the input.
enum E<'a> { Bad(&'a str) }is cheap and viral: every function that can return it, every struct that can store it, and every caller that can log it inherits the lifetime. Own the data unless you have measured a reason not to.
Best Practices
- Return
Resultwhenever a correct caller can hit the failure. That is the same test as the previous lesson, read from the other side. If they cannot avoid it, they are entitled to be told about it.
- Make
Ean enum of what actually goes wrong. One variant per situation that a caller might reasonably handle differently. Fewer variants than that hides information; a variant per line of code exposes your implementation.
- Carry the offending values in the error.
TooLarge { key, value, max }writes the user's message for them.TooLargealone makes every caller reconstruct it.
- Derive
Debugon every error type, always. It is required forunwrap, formainreturningResult, and for any test that fails informatively. AddDisplayandstd::error::Errorfor anything public.
- Own your error data. Allocating a
Stringon the failure path is not a cost worth optimising, and a'staticerror type stays useful after the buffer it described is gone.
- Use
Result<(), E>for succeed-or-explain operations and write theOk(())explicitly rather than restructuring the function to avoid it.
- Use combinators for one-step transforms and
matchwhen the arms differ.map_errto change an error type is clear; a chain of five combinators that ends inunwrap_or_defaultis amatchthat lost its nerve.
- Alias repetitive error types. If every function in a module returns
Result<T, ConfigError>, definetype Result<T> = std::result::Result<T, ConfigError>and stop repeating yourself -- exactly whatio::Resultdoes.
Practice Exercises
- Add a boolean key. Extend the parser with
verbose = true, acceptingtrueandfalseand nothing else. Add whateverConfigErrorvariant you need, decide whether"TRUE"should be accepted, and say in a comment why you chose as you did.
- Put the location in the error. Give every
ConfigErrorvariant a line number, or wrapConfigErrorin a struct that carries one. Then remove theprintln!of the raw line frommainand confirm the messages are still locatable on their own.
- Flatten one arm with combinators. Rewrite the
"port"arm usingmapand nothing else, so that it is a single expression. Then rewrite the"workers"arm the same way and judge whether the result is clearer than thematchit replaced.
- Make it transactional. Change
mainso that no setting is applied unless every line is valid: collect the errors from a first pass over the lines, and only mutatesettingsif that collection is empty. Report what had to change aboutapply's signature to make this possible.