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.
Resultis 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 aStringor()(()is typically used withResultif you just wanted to return anErroccurred but not actually return anything)Result<i32, Box<dyn std::error::Error>>This will return either ai32or a Box (TLDR; A Box is stored on the heap, in our case: it’s needed because I’m usingstd::error::Errora 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
Resultis commonly used to portray anError