Skip to content

Instantly share code, notes, and snippets.

@durka
Forked from anonymous/playground.rs
Last active August 29, 2015 14:23
Show Gist options
  • Save durka/1a517140c78f2279e46c to your computer and use it in GitHub Desktop.
Save durka/1a517140c78f2279e46c to your computer and use it in GitHub Desktop.
Macro for making a struct with an automatic ::new()
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