In this lesson, you will learn how the Result enum acts as a container to force you to explicitly acknowledge both the success and the failure states of your code.
The Anatomy of Result
In Rust, error handling isn't an afterthought; it is baked into the type system through the Result enum. While Option tells you if a value exists or is "nothing," Result tells you if an operation completed successfully or failed for a specific reason.
If you peek into the standard library source code, you’ll see that Result is a generic enum defined like this:
enum Result<T, E> {
Ok(T),
Err(E),
}
This simple structure provides a powerful contract:
Ok(T): This variant represents success. It wraps a value of typeT. When you see this, it’s a guarantee that the operation performed as expected and the data you need is ready to be used.Err(E): This variant represents failure. It wraps a value of typeE, which describes what went wrong. Unlike languages that use "hidden" exceptions that bubble up unexpectedly,Resultforces you to handle thisErrcase before you can reach theTinside theOkvariant.
Why This Matters
By using two distinct generic types, T and E, Rust allows developers to tailor the success and error types to the specific needs of the function. For example, a file-reading function might return Result<String, std::io::Error>, while a simple math utility might return Result<f64, String>.
Because Result is an enum, you can use pattern matching (match) to "unwrap" the value safely:
let outcome: Result<i32, &str> = Ok(100);
match outcome {
Ok(value) => println!("Success: {}", value),
Err(message) => println!("Failed: {}", message),
}
By forcing this "branching" behavior, the language ensures that your program cannot accidentally try to use data that resulted from a failure, effectively eliminating the common category of bugs where an error is ignored or forgotten.
Key Takeaway: The Result type is a generic enum that acts as a mandatory checkpoint, ensuring that success (Ok) and failure (Err) are both explicitly handled before the program logic can proceed.