Last active
August 29, 2015 14:15
-
-
Save kbknapp/7989c3975288be9ed59f to your computer and use it in GitHub Desktop.
Example method chaining 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
// 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