Hello! In our last lesson, we mastered pattern matching with match and if let, which gave us a safe way to handle different enum variants. We saw a glimpse of the Result enum and how if let Ok(...) could handle a success case. Today, we'll explore that concept fully.
This lesson focuses on one of Rust's most important features for building reliable software: handling recoverable errors. Many operations, especially in systems and embedded programming, can fail—files might not exist, network connections can drop, hardware might not respond. We'll learn how to represent these potential failures using the Result enum and how to write clean, robust code to manage them using the powerful ? operator. This is the final topic in our Rust fundamentals module and a critical skill for writing any real-world Rust application.
The Result Enum for Recoverable Errors
In languages like C, functions often signal errors by returning special values like -1 or a null pointer, which are easy to forget to check. In C++, exceptions are used, which can introduce non-local control flow that's sometimes hard to reason about. Rust takes a different approach by encoding the possibility of failure directly into the type system with the Result<T, E> enum.
The Result enum has two variants:
Ok(T): The operation succeeded, and the variant holds the resulting value of typeT.Err(E): The operation failed, and the variant holds an error value of typeE.
This design forces you, the programmer, to deal with the possibility of failure at compile time. The compiler won't let you pretend an operation can't fail if its return type is Result.
Recoverable Errors with Result
This first section of Chapter 9 from "The Rust Programming Language" book formally introduces the Result enum and its generic T and E parameters.
Read the beginning of the chapter, up to the code in Listing 9-4. Focus on the definition of the enum and the example of File::open, which returns a Result<std::fs::File, std::io::Error>.
Here is a simple visual example of a function returning a Result. The function get_day_of_the_week returns either a successful Ok variant containing a string slice, or an Err variant if the input number is invalid.

Handling Result with match
Since Result is an enum, we can use the match expression we learned about in the previous lesson to handle its variants. This is the most fundamental way to deal with a Result.
The "Let's Get Rusty" video on error handling provides a clear walkthrough of this concept.
First, watch the segment that introduces the Result enum from this point. Then, watch the section on using match to handle a Result from File::open. Notice how a nested match can be used to react differently to specific kinds of errors.
The video showed a powerful pattern: matching on the error's kind. This lets you build more robust logic, such as attempting to create a file if it was not found, but panicking on other errors like a permissions issue.
Here is the same logic explained in the Rust book.
Recoverable Errors with Result
This reading from the Rust book provides a textual walkthrough of the File::open example.
First, read the section that shows a basic match on the Result from File::open. Next, read the following section, which introduces the more complex logic of using a nested match to check error.kind(). This demonstrates how to handle different failure modes distinctly.
While powerful, you can see that nested match expressions can become quite verbose. Before we look at how to improve this, let's briefly cover two common, but potentially dangerous, shortcuts.
Shortcuts: unwrap and expect
The Result type provides a couple of helper methods for situations where you believe an error is impossible or unrecoverable.
unwrap(): This method is a shortcut. If theResultisOk(value), it returnsvalue. If it'sErr, itpanic!s and crashes the program.expect("message"): This works just likeunwrap, but it lets you provide a custom panic message, which is much better for debugging.
Rust Error Handling: A Practical Guide to Result
This segment from Max Taylor's video on Result gives a direct warning about these methods.
Watch the short section advising against unwrap and expect.
The key takeaway is that you should generally avoid unwrap and expect in production code. They are best used in tests, quick prototypes, or in the rare cases where your program's logic guarantees an operation cannot fail. For everything else, you should either handle the error or propagate it.
Propagating Errors with the ? Operator
Often, the function where an error occurs doesn't have the right context to handle it. In these cases, you should propagate (or return) the error to the calling function. The caller has more information and can decide whether to retry, use a default value, or report the error to the user.
You could do this manually with a match statement, but Rust provides a much more ergonomic solution: the question mark operator (?).
The ? operator is syntactic sugar for error propagation. When placed after an expression that returns a Result:
- If the result is
Ok(value), thevalueis extracted and the program continues. - If the result is
Err(error), the function stops execution immediately and returns theErr(error)to its caller.
This makes for exceptionally clean error-handling code.
Recoverable Errors with Result
This part of the Rust book brilliantly contrasts the manual, verbose way of propagating errors with the concise ? operator.
First, read the section on propagating errors manually using match. Pay attention to the boilerplate code required. Then, read the section on the ? operator. Compare the code in Listing 9-7 and 9-8 to the manual version. The improvement in readability and conciseness is significant.
There's one important rule: you can only use the ? operator in a function that returns a Result (or an Option). If you try to use it in a function that returns something else (like the unit type () in our simple main functions so far), the compiler will give you an error. We'll see how to make main return a Result shortly.
The ? Operator and Error Conversion
The ? operator has another superpower: it can convert error types. When you call ? on a Result, if it's an Err, the operator implicitly calls the from function on the error value. This function comes from the From trait, a standard library trait used for type conversions.
This is incredibly useful when you have a function that calls multiple other functions, each of which might return a different type of error. You can define a single, custom error enum for your function and implement the From trait to convert each of the underlying error types into your custom one.

This pattern is fundamental in embedded development, where a driver for a specific component will often define its own error type and convert errors from the underlying hardware communication layer (like SPI or I2C) into its own variants.
Error Handling - Rust Embedded Drivers Book
This chapter from the "Rust Embedded Drivers Book" shows a perfect, practical example of this pattern for a MAX7219 LED driver.
Start by looking at how a custom Error enum is defined to represent all possible failures in the driver. Next, read the crucial section on converting SPI errors. This impl<E> From<E> for Error block is what allows the ? operator to transparently handle errors from the SPI bus. Finally, see how a Result type alias is used. This is a common ergonomic improvement that makes function signatures cleaner.
This pattern—defining a custom error enum, implementing From for underlying error types, and using ? for propagation—is the bedrock of idiomatic error handling in Rust libraries and applications.
Returning Result from main
As mentioned, ? only works in functions that return Result or Option. So what about main? Fortunately, the main function is allowed to return a Result. This is very convenient for simple applications.
Recoverable Errors with Result
This final section from the Rust book shows how to change main's signature to enable the use of the ? operator.
Read the section on how to change main. Pay attention to the Box<dyn Error> type, which is a trait object that can represent "any kind of error." This is a common choice for the error type in application-level main functions.
When a main function returns Ok(()), the program exits successfully with a code of 0. If it returns an Err value, it exits with a non-zero status code and Rust prints the error for you.
Conclusion
You have now completed the Rust fundamentals module! This lesson on error handling is a crucial piece of the puzzle, enabling you to write programs that are not just correct in the "happy path" but also robust in the face of failure.
Here are the main takeaways from this lesson:
- Rust enforces explicit error handling using the
Result<T, E>enum, which hasOk(T)for success andErr(E)for failure. - You can handle
Resultvalues withmatchexpressions, allowing for fine-grained control over different error kinds. - The
?operator is the idiomatic and concise way to propagate errors, returning anErrimmediately from a function while unwrapping the value from anOk. - The
?operator leverages theFromtrait to automatically convert between different error types, which is essential for composing functions that can fail in different ways. - You can return a
Resultfrommainto use the?operator for convenient error handling in top-level application code.
In our next lesson, we will begin our exploration of abstraction in Rust. We will start by formally learning about traits, which are Rust's way of defining shared behavior. We've just had a preview with the From trait, and next time we'll learn how to define and implement our own.