Result

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 a String or () (() is typically used with Result if you just wanted to return an Err occurred but not actually return anything)
  • Result<i32, Box<dyn std::error::Error>> This will return either a i32 or a Box (TLDR; A Box is stored on the heap, in our case: it’s needed because I’m using std::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 an Error