Skip to content

Instantly share code, notes, and snippets.

@durka
Forked from anonymous/playground.rs
Last active August 29, 2015 14:23
Embed
What would you like to do?
Macro that creates fn impls on a tuple
// due to Enamex on #rust
macro_rules! overload {
( $trait_name:ident ($($args:ident : $typs:ty),+) => $( fn $fn_name:ident -> $ret:ty => $body:block );+ ) => {
overload!(INTERNAL:DUPLICATE $trait_name ( ($($args),+) ($($args),+) : ($($typs),+) ($($typs),+) ) => $( fn $fn_name -> $ret => $body );+ );
};
(INTERNAL:DUPLICATE $trait_name:ident ( $all_args:tt ($($args:ident),+) : $all_typs:tt ($($typs:ty),+) ) => $( fn $fn_name:ident -> $ret:ty => $body:block );+ ) =>
{
trait $trait_name {
$(
fn $fn_name (self) -> $ret;
);+
}
impl $trait_name for ($($typs),+) {
$(
fn $fn_name(self) -> $ret {
let overload!(INTERNAL:EVAL_TUPLE $all_args) = self;
$body
}
)+
}
};
(INTERNAL:EVAL_TUPLE ($($a:ident),+)) => { ($($a),+) }
}
overload! {
Trial1 (s: i32, ss: char) =>
fn try_me -> char => {
if s < 6 { ss } else { '💩' }
}
}
fn main() {
println!("Hello, world!");
println!("{}", (42, '☃').try_me());
println!("{}", (-42, '☃').try_me());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment