Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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