Skip to content
tezvyn:
Menu

Handling Errors with Rust's Result Enum

Source: doc.rust-lang.orgEasyHow cards are made

Rust's Result enum makes error handling explicit. Instead of returning a value that might be an error code, functions return either Ok(value) or Err(error). It's used for recoverable failures like I/O.

Why it exists

To prevent bugs from ignored errors. In many languages, functions signal errors with special return values (like -1 or null) that are easy to forget to check. Rust's Result type, combined with the compiler's #[must_use] check, issues a warning if a potential failure is not handled, making errors explicit.

The mental model

Think of Result<T, E> as a sealed box that contains either a successful outcome (Ok(T)) or a failure (Err(E)). To get the value out, you must explicitly open the box and acknowledge both possibilities. This moves error handling from a runtime discipline problem to a compile-time requirement.

How it works

Result is an enum with two variants: Ok(T) for a success value of type T, and Err(E) for an error of type E. You can handle it with a match expression to explicitly branch your code for each case. For more concise handling, Rust provides methods like is_ok(), map(), and and_then(). The most idiomatic tool is the question mark operator (?). Placing ? after a function call that returns a Result will either unwrap the Ok value and continue, or immediately return the Err from the current function, propagating the error up the call stack.

When to use it

Use Result for any error that is expected and recoverable. This is the standard for almost all fallible operations in Rust, such as file I/O (a file might not exist), network requests (a server might be down), or data parsing (input might be malformed).

When not to use it

For unrecoverable errors, a panic! is more appropriate. These represent bugs in the program logic, like an out-of-bounds array access, where continuing execution is impossible or nonsensical. Result is for expected, handleable failures; panic! is for unexpected, catastrophic ones.

One canonical example

A function parsing a version number from a byte stream returns a Result. If the first byte is 1, it returns Ok(Version::Version1). If the header is empty, it returns Err("invalid header length"). The calling code must then use a match or ? to handle both the success and error cases, preventing an unhandled error from going unnoticed.

Interview question

When is it most appropriate to use Rust's Result enum for error handling?

  • a.When a function might encounter an expected, recoverable failure.Correct
  • b.To return a special value like null or -1 when an operation fails.
  • c.To handle all potential runtime exceptions and prevent program crashes.
  • d.When an operation results in an unrecoverable error, indicating a program bug.
Why?

The card explicitly states that Result should be used for 'any error that is expected and recoverable,' such as file I/O or network requests. Option D describes when to use panic!, not Result, as panic! is for unrecoverable, catastrophic errors.

Just read this? Test yourself on what you have been reading.

Read the original → doc.rust-lang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.

See open roles