Skip to content

Instantly share code, notes, and snippets.

@kbknapp
Last active August 29, 2015 14:15
Show Gist options
  • Save kbknapp/7989c3975288be9ed59f to your computer and use it in GitHub Desktop.
Save kbknapp/7989c3975288be9ed59f to your computer and use it in GitHub Desktop.
Example method chaining macro
// credit to /u/tyoverby of reddit
macro_rules! chain(
($inp:expr; $(. $call:ident($($e:expr),*))*) => (
{
let mut tmp = $inp;
$(
tmp.$call($($e),*);
)*
tmp
}
);
($inp:expr; $(. $call:ident::<$($t:ty),*>($($e:expr),*))*) => (
{
let mut tmp = $inp;
$(
tmp.$call::<$($t),*>($($e),*);
)*
tmp
}
);
);
fn main() {
let a = vec![1u32, 2, 3];
let b = chain!(a; .push(50));
let c = chain!(b;
.push(50)
.push(100)
.push(150));
assert_eq!(c, vec![1, 2, 3, 50, 50, 100, 150]);
println!("OK")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment