Recoverable errors
As we have already said, the majority of error handling in Rust is done via two generic types, Option
and Result
. They act as wrapper types in the sense that it is recommended that APIs that can fail return the actual values by putting them inside these types. These types are built with a combination of enums and generics. As an enum, they get the ability to store a success state and an error state, while generics allow them to specialize at compile time so that they store any value in either state. These types also come with a lot of convenient methods (commonly known as combinators) implemented on them, allowing you to consume, compose, or transform the inner values easily. One thing to note about the Option
and Result
types is that they are ordinary types from the standard library in the sense that they aren't compiler built-ins that are treated differently by the compiler. Anyone can create a similar error abstraction using the power of enums and generics. Let's start...