Created
July 16, 2020 08:12
-
-
Save asaaki/ae5d75e92278b3dec5f3a3b03b1c8bcd to your computer and use it in GitHub Desktop.
Rust: Result types for quick prototyping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=17187eac71474f2d03461d2947a06b57