Skip to content

Instantly share code, notes, and snippets.

Created July 30, 2015 18:20
Show Gist options
  • Save anonymous/e16101976824f2cf26bf to your computer and use it in GitHub Desktop.
Save anonymous/e16101976824f2cf26bf to your computer and use it in GitHub Desktop.
Shared via Rust Playground
macro_rules! as_stmt { ($s:stmt) => ($s) }
macro_rules! as_item { ($s:item) => ($s) }
macro_rules! declare_array {
($storage:ident $n:ident: [$t:ty] = [$($vals:expr),*]) => {
declare_array!(_parse $storage $n, $t, 0, [], $($vals),*);
};
(_parse $s:ident $n:ident, $t:ty, $size:expr, [$($accs:expr),*], $val:expr, $($vals:expr),+) => {
declare_array!(_parse $s $n, $t, $size+1, [$($accs,)* $val], $($vals),*);
};
(_parse $s:ident $n:ident, $t:ty, $size:expr, [$($accs:expr),*], $val:expr) => {
declare_array!(_output $s $n, $t, $size+1, [$($accs,)* $val]);
};
(_parse $s:ident $n:ident, $t:ty, $size:expr, $acc:tt, ) => {
declare_array!(_output $s $n, $t, $size, $acc);
};
(_output let $n:ident, $t:ty, $size:expr, $acc:tt) => {
as_stmt!(let $n: [$t; $size] = $acc)
};
(_output static $n:ident, $t:ty, $size:expr, $acc:tt) => {
as_item!(static $n: [$t; $size] = $acc;);
};
}
declare_array!(static ARR: [i32] = [1, 2, 3]);
fn main() {
declare_array!(let arr: [i32] = [4, 5, 6]);
println!("{:?}", ARR);
println!("{:?}", arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment