Sub topic 3
Result<T, E>: an operation that may fail
This chapter assumes you know Rust enums and match, basic generics, and the idea that a function can return a value of a type you choose. It builds on the previous chapter, where Option<T> represented a value that might be missing. Result<T, E> covers a different case: the operation ran, and it either produced a value or failed for a reason you want to know.
What Result is
Result is an ordinary enum in the standard library with two variants:
enum Result<T, E> {
Ok(T),
Err(E),
}Ok(T) carries the success value. Err(E) carries an error value. Both Result and its variants are in the prelude, so you write Ok(5) and Err(...) without imports.
Nothing about Result is built into the compiler beyond the ? operator, which later chapters cover. It follows the same rules as any enum you define. It is moved or copied like any other value, and you inspect it with match.
A first example
The standard library uses Result wherever an operation can fail on bad input. Parsing is the usual case:
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)
Err(ParseIntError { kind: InvalidDigit })A failed parse is a normal return value. The function does not throw, and the caller cannot skip over the failure. To get at the u16, the caller has to deal with the Err case.
Writing your own fallible function
You create a Result by wrapping a value in Ok or Err. The function signature declares both types, so a reader sees how the function can fail without reading its body.
fn withdraw(balance: u32, amount: u32) -> Result<u32, String> {
if amount > balance {
Err(format!("insufficient funds: have {balance}, need {amount}"))
} else {
Ok(balance - amount)
}
}
fn main() {
match withdraw(100, 30) {
Ok(left) => println!("remaining: {left}"),
Err(msg) => println!("failed: {msg}"),
}
match withdraw(100, 130) {
Ok(left) => println!("remaining: {left}"),
Err(msg) => println!("failed: {msg}"),
}
}The match must cover both variants, or the code does not compile. The compiler checks that you handled the failure path.
How a Result flows through code
Choosing the error type E
The E in Result<T, E> is your choice. Each option trades simplicity against what the caller can do with the error.
| Error type | Good for | Limitation |
|---|---|---|
| `String` or `&'static str` | Scripts, prototypes, one-off messages | Callers can only print it, or compare text |
| A standard library error such as `ParseIntError` or `std::io::Error` | Thin wrappers around one std call | Cannot describe failures from your own logic |
| A custom enum | Libraries and code where callers react to specific failures | More code to write |
| `Box<dyn Error>` | Applications that mix many error sources | The concrete type is hidden |
Later chapters build the last two. For now, remember that callers can only make decisions based on what the error type exposes. A String forces them to parse your message to tell cases apart. An enum lets them match on the cause.
Result or Option?
Use Option<T> when absence is a normal outcome and there is only one reason for it. A lookup in a map that finds nothing is an example. Use Result<T, E> when the caller may need to know why the operation failed.
"abc".parse::<u16>() could return Option<u16>, but then you could not tell an empty string from an overflow like "99999". With Result, the error says which one happened:
fn main() {
println!("{:?}", "".parse::<u16>());
println!("{:?}", "99999".parse::<u16>());
}This prints Err(ParseIntError { kind: Empty }) and then Err(ParseIntError { kind: PosOverflow }).
Errors from the standard library
Many standard library functions that touch the outside world return std::io::Result<T>. This is a type alias for Result<T, std::io::Error>. You will see the same pattern in many crates, which define a local alias such as type Result<T> = std::result::Result<T, MyError>; so signatures stay short.
use std::fs;
fn main() {
match fs::read_to_string("does-not-exist.txt") {
Ok(text) => println!("read {} bytes", text.len()),
Err(e) => println!("could not read file: {e}"),
}
}On Linux, this prints could not read file: No such file or directory (os error 2). The exact wording depends on the operating system. The error also carries a machine-readable kind, available through e.kind(), so code can treat a missing file differently from a permission problem.
Edge cases and gotchas
Operations with no success value
When an operation succeeds without producing anything, use Result<(), E>. The Ok(()) value holds the unit type, which carries no data:
fn check_age(age: u8) -> Result<(), String> {
if age < 18 {
Err(String::from("must be 18 or older"))
} else {
Ok(())
}
}
fn main() {
println!("{:?}", check_age(20));
println!("{:?}", check_age(12));
}Type inference needs both types
A bare Ok(5) fixes only T. The compiler cannot guess E from it, so this fails with "type annotations needed":
fn main() {
let r = Ok(5);
println!("{}", r.is_ok());
}Annotate the binding, and the code compiles:
fn main() {
let r: Result<i32, String> = Ok(5);
println!("{}", r.is_ok());
}Inside a function that declares its return type, inference usually works because the return type supplies both parameters.
Ignoring a Result triggers a warning
Result is marked #[must_use]. If you call a function that returns one and discard the value, the compiler warns:
fn main() {
withdraw_all();
}
fn withdraw_all() -> Result<(), String> {
Err(String::from("account frozen"))
}The warning reads unused Result that must be used. If you really intend to ignore the outcome, say so with let _ = withdraw_all();. Be careful with this form. It silences the warning and also hides a failure you may have wanted to see.
Size of the error type
A Result is as large as its larger variant plus a tag, so a big E makes every Ok return large too. Clippy's result_large_err lint warns about this when E grows past a threshold, 128 bytes by default. If you hit it, box the error or store its large fields behind a pointer.
Summary of the model
Result<T, E>has two variants,Ok(T)andErr(E).- A function's signature states both what success looks like and what failure looks like.
- Callers must handle the
Errcase, or explicitly choose not to. - The choice of
Edecides how much callers can do with a failure. - Use
ResultoverOptionwhen the reason for failure matters.
The next chapter covers the ways to handle each variant: match, if let, and let else.
Exercise
Write a function half(n: i32) -> Result<i32, String> that returns Ok(n / 2) when n is even and an Err with the message "odd number" when it is odd. Then explain why let r = Err("bad"); fails to compile on its own, and give one way to fix it.
Show answer
fn half(n: i32) -> Result<i32, String> { if n % 2 == 0 { Ok(n / 2) } else { Err(String::from("odd number")) } }. The line let r = Err("bad"); fixes only the error type E as &str. The compiler cannot infer the success type T, so it reports "type annotations needed". Fix it with an annotation such as let r: Result<i32, &str> = Err("bad");, or by using r in a context that determines T.