Last active
August 29, 2015 13:56
-
-
Save jfager/8901713 to your computer and use it in GitHub Desktop.
Avoiding if_ok! repetition with a macro
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
#[feature(macro_rules)]; | |
extern mod std; | |
use std::io::IoResult; | |
macro_rules! if_ok_all( | |
//Note that the Err case in these just returns, b/c this little demo is just running | |
//from main and so can't return an IoResult. | |
( $($a:expr <- $e:expr),+ ) => ( | |
{ $( $a = match $e { Ok(e) => e, Err(_) => return } );+ } | |
); | |
( $($a:ident = $e:expr),+ ) => ( | |
let ( $( $a ),+ ) = ( $(match $e { Ok(e) => e, Err(_) => return }),+ ); | |
); | |
) | |
fn something() -> IoResult<bool> { Ok(true) } | |
fn something_else() -> IoResult<~str> { Ok(~"hello") } | |
struct foo { | |
a: bool, | |
b: ~str | |
} | |
fn main() { | |
let mut f = foo { a: false, b: ~"" }; | |
if_ok_all!( | |
f.a <- something(), | |
f.b <- something_else() | |
); | |
if_ok_all!( | |
a = something(), | |
b = something_else() | |
); | |
println!("{:?}, {:?}, {:?}", f, a, b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment