# 数组 – 如何使用函数初始化数组？

```macro_rules! array {
(\$v: expr; 1) => ([\$v]);
(\$v: expr; 2) => ([\$v, \$v]);
(\$v: expr; 3) => ([\$v, \$v, \$v]);
(\$v: expr; 4) => ([\$v, \$v, \$v, \$v]);
(\$v: expr; 5) => ([\$v, \$v, \$v, \$v, \$v]);
// until 32
}

let a = array![Vec::new(); 3];```

```extern crate nodrop;

macro_rules! array {
(\$e: expr; \$n:expr) => (
{
use std::mem;
use std::ptr;
use nodrop::NoDrop;

struct ArrayBuilder<T> {
len: usize,
data: *mut T,
}

impl<T> Drop for ArrayBuilder<T> {
fn drop(&mut self) {
unsafe {
while self.len > 0 {
let offset = (self.len as isize) - 1;
self.len -= 1;
ptr::drop_in_place(self.data.offset(offset));
}
}
}
}

let mut v: NoDrop<[_; \$n]> = NoDrop::new(unsafe {
mem::uninitialized()
});
// helps type inference for v
if false { v[0] = \$e; }
let mut builder = ArrayBuilder {
len: 0,
data: (&mut *v as *mut _) as *mut _
};
unsafe {
for i in 0..\$n {
ptr::write(builder.data.offset(i as isize), \$e);
builder.len = i + 1;
}
}
builder.len = 0;
v.into_inner()
}
)
}

let a = array![Vec::new(); 3];```

```#[test]
fn test() {
static mut COUNT: usize = 0;

#[derive(Debug)]
struct X(usize);

impl Drop for X {
fn drop(&mut self) {
println!("drop {:?}", self.0);
}
}

impl X {
fn new() -> X {
unsafe {
if COUNT == 3 {
panic!();
}
let x = X(COUNT);
COUNT += 1;
x
}
}
}

array![X::new(); 6];
}```