Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created July 16, 2020 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/ae5d75e92278b3dec5f3a3b03b1c8bcd to your computer and use it in GitHub Desktop.
Save asaaki/ae5d75e92278b3dec5f3a3b03b1c8bcd to your computer and use it in GitHub Desktop.
Rust: Result types for quick prototyping
/*
IMPORTANT NOTE: It is not a good idea to use this pattern in production code!
*/
// Q&D way of catching all errors without worrying about their types at compile time
// @see https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/boxing_errors.html
type GenericResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// type alias to make it reaaaaalllly concise
type MainResult = GenericResult<()>;
// for functions, which should return a result, but can never fail:
type OkResult<T> = Result<T, core::convert::Infallible>;
#[derive(Debug, Clone)]
struct CustomError(String);
impl std::fmt::Display for CustomError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "custom error raised: {}", self.0)
}
}
impl std::error::Error for CustomError {}
fn infallible_call() -> OkResult<usize> {
Ok(42)
}
fn custom_error() -> Result<(), CustomError> {
Err(CustomError("test custom error".into()))
}
// `main` catches everything and just fails;
// so the exact error type is also not that important here, right? ;-)
fn main() -> MainResult {
let _a = infallible_call()?; // cannot return an error (Infallible)
// testing the display impl
match custom_error() {
Ok(_) => (),
Err(e) => println!("display test: {}", e),
}
let _c = custom_error()?; // returns our custom error
let _f = std::fs::read("doesnotexists")?; // returns an std::io::Error
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment