Skip to content

Instantly share code, notes, and snippets.

@jfager
Last active August 29, 2015 13:56
Show Gist options
  • Save jfager/8901713 to your computer and use it in GitHub Desktop.
Save jfager/8901713 to your computer and use it in GitHub Desktop.
Avoiding if_ok! repetition with a macro
#[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