Rust Reference ยท Option and Result
Rust Result<T, E> type
Reference for Rust Result<T, E>: the enum behind recoverable errors, with Ok and Err, matching, the ? operator, type aliases and the must_use rule.
Result<T, E> is the standard type for operations that can fail. It is an ordinary enum with two variants: Ok(T) carries the success value and Err(E) carries an error. Because failure is part of the return type, the compiler makes you deal with it; you cannot accidentally use an Err as if it were the success value.
Result is marked #[must_use], so ignoring a returned Result produces a warning. Both Ok and Err are in the prelude, so you write them without a path. For absence that is not an error, use Option<T> instead.
enum Result<T, E> { Ok(T), Err(E), }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub enum Result<T, E> { Ok(T), Err(E), } fn read() -> Result<String, std::io::Error> { /* ... */ }
| Part | Description |
|---|---|
T |
The type of the success value inside Ok. |
E |
The type of the error inside Err. Often a custom enum, io::Error, or Box<dyn Error>. |
Common constructors: Ok(value) and Err(error). There is no Default for Result.
Panics: the type itself never panics; unwrap, expect and indexing-like helpers on it do (see Result unwrap family).
Usage notes
- Pattern matching is exhaustive. A
matchon aResultmust cover bothOkandErr, or use a catch-all arm.if let Ok(v) = randlet Ok(v) = r else { ... }handle one side. - The
?operator returns early with the error (converted throughFrom) and otherwise unwraps theOkvalue. It is the default way to chain fallible calls; see the?operator. - Common aliases:
std::io::Result<T>isResult<T, io::Error>,std::fmt::ResultisResult<(), fmt::Error>, and your own crate usually definestype Result<T> = std::result::Result<T, MyError>. maincan returnResult<(), E>whenE: Debug. AnErrmakes the process printError: {e:?}to stderr and exit with code 1. See Exit codes.Result<(), E>is the "can fail, returns nothing" type.Ok(())is how you report success.- Size:
Result<T, E>is as large as the larger variant plus a tag, though the compiler squeezes the tag into unused bit patterns where it can (for exampleResult<Box<T>, ()>is pointer-sized). Resultis notOption. Convert withok()andok_or.- Do not ignore it:
let _ = might_fail();silences the warning on purpose;might_fail();alone does not. - Collecting many results into one
Result<Vec<_>, _>is covered in Collecting Results.