Result: Handling Recoverable Errors in Rust
Rust handles recoverable errors with the `Result<T, E>` enum, forcing you to deal with both success (`Ok`) and failure (`Err`) paths. This shows up when a function like `File::open` might fail.
WHY IT EXISTS To handle errors that are expected and recoverable without crashing the whole program. Instead of exceptions or returning special values like null, Rust functions signal potential failure explicitly in their return type, forcing the caller to acknowledge and handle it.
THE MENTAL MODEL Think of a Result as a sealed box that can contain either a success value (Ok) or an error value (Err). You cannot get the value inside without first explicitly opening the box and checking which variant you received. This prevents you from accidentally using a value from a failed operation.
HOW IT WORKS The Result<T, E> enum has two variants: Ok(T) holds a success value of type T, and Err(E) holds an error value of type E. A function like File::open("hello.txt") returns a Result<std::fs::File, std::io::Error>. You use a match expression to handle both possibilities. The Ok(file) arm gives you the file handle, while the Err(error) arm gives you the error information to act upon.
WHEN TO USE IT Use Result as the return type for any function you write that can fail in a way the caller might want to recover from. This is the standard, idiomatic pattern for I/O operations, parsing, network requests, or any fallible conversion where failure is a predictable outcome.
WHEN NOT TO USE IT For unrecoverable errors where the program cannot possibly continue in a sane state, panicking is more appropriate. These are typically bugs, like an index-out-of-bounds access, which indicate a logic error in the program that should be fixed. Result is for expected, recoverable failures, not programming mistakes.
ONE CANONICAL EXAMPLE Opening a file that might not exist. The code let file_result = File::open("data.txt"); gives you a Result. You can then match on it: match file_result { Ok(file) => file, Err(error) => ... }. Inside the Err arm, you can have another match on error.kind() to check if the error was ErrorKind::NotFound and create the file, or panic on other errors like permission denied. This allows for fine-grained error response instead of a simple crash.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.