yrt/lib.rs
1/// Extracts an error from a Result or propogates its value. This macro
2/// operates like the inverse of the `try!` macro.
3///
4/// In case of the `Ok` variant, it retrieves the inner value. `yrt!` then
5/// performs conversion using `From`. This provides automatic conversion
6/// for general value propogation. The resulting value is then immediately
7/// returned.
8///
9/// Because of the early return, `yrt!` can only be used in functions that
10/// return `Result`.
11///
12/// # Examples
13///
14/// ```
15/// use std::io;
16/// use std::fs::File;
17/// use std::io::prelude::*;
18/// use yrt::yrt;
19///
20/// // The preferred method of quick returning Errors
21/// fn early_return_success() -> Result<File, ()> {
22/// let _ = yrt!(File::open("my_best_friends.txt"));
23///
24/// // The unwrap is just for example code
25/// Ok(File::create("my_best_friends.txt").unwrap())
26/// }
27///
28/// // This is equivalent to:
29/// fn write_to_file_using_match() -> Result<File, ()> {
30/// let _ = match File::open("my_best_friends.txt") {
31/// Ok(v) => return Ok(From::from(v)),
32/// Err(e) => e,
33/// };
34///
35/// Ok(File::create("my_best_friends.txt").unwrap())
36/// }
37/// ```
38#[macro_export]
39macro_rules! yrt {
40 ($expr:expr) => {
41 match $expr {
42 ::std::result::Result::Ok(val) => return ::std::result::Result::Ok(::std::convert::From::from(val)),
43 ::std::result::Result::Err(err) => err
44 }
45 };
46 ($expr:expr,) => {
47 $crate::yrt!($expr)
48 };
49}