-
-
Save durka/1a517140c78f2279e46c to your computer and use it in GitHub Desktop.
Macro for making a struct with an automatic ::new()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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