Rust has a way to return if something was successful with a value (Ok
), or an error and what that error was/is (Err
), using Result
.
Result
can be used in cases where you either want to return a value, or the error that occurred.
Result
is similar but quite different to Option
Result
will want the type for Ok
, and the type for Err
Some examples:
Result<String, ()>
This will return either aString
or()
(()
is typically used withResult
if you just wanted to return anErr
occurred but not actually return anything)Result<i32, Box<dyn std::error::Error>>
This will return either ai32
or a Box (TLDR; A Box is stored on the heap, in our case: it’s needed because I’m usingstd::error::Error
a trait, to try and cover a collection of possible errors)
I highly recommend looking at:
- anyhow (Useful for binaries that use/encounter errors)
- thiserror (Useful for libraries that make/define errors)
Both of these crates are great time savers and awesome utilities for making and dealing with errors.
Why the sudden push to dealing with errors? Because
Result
is commonly used to portray anErr
or