I'm trying to initialize a big array of elements with the same initializer. 64 elements is just an example — I want to make it at least 16k. Unfortunately a simple
let array : [AllocatedMemory<u8>; 64] = [AllocatedMemory::<u8>{mem:&mut []};64];
won't work because the AllocatedMemory
struct does not implement Copy
error: the trait `core::marker::Copy` is not implemented for the type `AllocatedMemory<'_, u8>` [E0277]
let array : [AllocatedMemory<u8>; 64] = [AllocatedMemory::<u8>{mem:&mut []}; 64];
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So I tried macros to no avail:
struct AllocatedMemory<'a, T: 'a> {
mem: &'a mut [T],
}
macro_rules! init_memory_helper {
(1, $T : ty) => { AllocatedMemory::<$T>{mem: &mut []} };
(2, $T : ty) => { init_memory_helper!(1, $T), init_memory_helper!(1, $T) };
(4, $T : ty) => { init_memory_helper!(2, $T), init_memory_helper!(2, $T) };
(8, $T : ty) => { init_memory_helper!(4, $T), init_memory_helper!(4, $T) };
(16, $T : ty) => { init_memory_helper!(8, $T), init_memory_helper!(8, $T) };
(32, $T : ty) => { init_memory_helper!(16, $T), init_memory_helper!(16, $T) };
(64, $T : ty) => { init_memory_helper!(32, $T), init_memory_helper!(32, $T) };
}
macro_rules! init_memory {
(1, $T : ty) => { [init_memory_helper!(1, $T)] };
(2, $T : ty) => { [init_memory_helper!(2, $T)] };
(4, $T : ty) => { [init_memory_helper!(4, $T)] };
(8, $T : ty) => { [init_memory_helper!(8, $T)] };
(16, $T : ty) => { [init_memory_helper!(16, $T)] };
(32, $T : ty) => { [init_memory_helper!(32, $T)] };
(64, $T : ty) => { [init_memory_helper!(64, $T)] };
}
fn main() {
let array: [AllocatedMemory<u8>; 64] = init_memory!(64, u8);
println!("{:?}", array[0].mem.len());
}
The error message is
error: macro expansion ignores token `,` and any following
(64, $T : ty) => { init_memory_helper!(32, $T), init_memory_helper!(32, $T) };
note: caused by the macro expansion here; the usage of `init_memory_helper!` is likely invalid in expression context
Is there any way to initialize this array without cut and pasting every initializer?