`Result`
Result<T, E> is Ok(T) or Err(E). It is the standard return type for a computation that can fail, and the type ? knows how to unwrap.
Detailed Explanation
Result<T, E> is an enum. Ok(value) is the success. Err(error) is the failure, and E holds the reason. A function that opens a file returns Result<File, io::Error>, not a file that might be invalid and a global errno. The caller must handle both arms or pass the problem on with ?.
E is a type you choose. The standard library uses dedicated error types: io::Error, fmt::Error, ParseIntError. Your crate can use an enum of its own failure cases, a boxed dyn Error, or a library type from thiserror or anyhow. The important part is that the reason travels with the Err, unlike Option, which only says absence.
The method set mirrors Option and adds error-specific helpers. map transforms Ok. map_err transforms Err. and_then chains another fallible call. unwrap and expect panic on Err. unwrap_or_else computes a fallback from the error. ok turns Result into Option, dropping the error — useful at a boundary, harmful in the middle of a pipeline.
? is the usual way to propagate. In a function that returns Result<_, E>, let file = File::open(path)?; returns early on Err after converting the error with From. That conversion is why a function can call I/O, parse integers, and still return one E: you implement From<io::Error> for E and From<ParseIntError> for E.
A Result in a public API is a promise. Changing E is a breaking change. Changing an Ok payload is a breaking change. Do not return Result<T, String> in a library unless the string is the entire contract; callers cannot match on a string reliably. Do not return Result<T, ()> unless you truly have nothing to say.
When you return Result: I/O, parse, any work that can fail for a reason the caller might handle. When you panic: a broken invariant, a bug. When you return Option: absence without a failure.
Code Examples
fn port(raw: &str) -> Result<u16, std::num::ParseIntError> {
let n = raw.parse::<u16>()?;
Ok(n)
}
fn main() {
println!("{:?}", port("8080")); // prints: Ok(8080)
println!("{:?}", port("nope").map_err(|e| e.to_string()));
// prints: Err("invalid digit found in string")
}Common Gotchas
`?` only works in functions that return `Result` or `Option`
In `main` before Rust 2018 / without `-> Result`, `?` is illegal. Return `Result` from `main`, or `match`.
`unwrap` on `Err` panics with the error's `Debug`
Fine in examples and tests. In a server it is a crash. Propagate or map the error.
`Result<T, String>` is a weak library API
Callers cannot match variants. Use a dedicated error enum, or `anyhow` in an application crate.
`map_err` is for changing `E`, not for logging and forgetting
Log at the boundary where you handle the error, not in every `map_err` along the way.