Skip to content

Instantly share code, notes, and snippets.

Created June 21, 2015 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/dc79a46b01d759d24884 to your computer and use it in GitHub Desktop.
Save anonymous/dc79a46b01d759d24884 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
// 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