Skip to content

Instantly share code, notes, and snippets.

Created June 22, 2015 02:13
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/b729a90eb0e37fe03f5c to your computer and use it in GitHub Desktop.
Save anonymous/b729a90eb0e37fe03f5c to your computer and use it in GitHub Desktop.
Shared via Rust Playground
macro_rules! as_item {
($i:item) => ($i);
}
macro_rules! struct_with_constructor {
(
$(#[$meta:meta])*
struct $name:ident {
$($arg:ident : $typ:ty),*;
$(fn $fn_name:ident $args:tt $(-> $ret_ty:ty)* { $($fn_body:tt)* })*
}
) => {
$(#[$meta])*
struct $name {
$($arg : $typ),*
}
as_item! {
impl $name {
fn new($($arg : $typ),*) -> $name {
$name { $($arg : $arg),* }
}
$(fn $fn_name $args $(-> $ret_ty)* {$($fn_body)*})*
}
}
}
}
struct_with_constructor!(
#[derive(Copy, Clone, Debug)]
struct Matrix {
rows: i32,
cols: i32;
fn numel(self) -> i32 { self.rows * self.cols }
}
);
fn main() {
let m = Matrix::new(3, 4);
println!("{}", m.numel());
println!("{:?}", m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment