我正在尝试使用相同的初始化程序初始化大量元素。64 个元素只是一个例子——我想让它至少 16k。不幸的是一个简单的
let array : [AllocatedMemory<u8>; 64] = [AllocatedMemory::<u8>{mem:&mut []};64];
不会工作,因为AllocatedMemory
结构没有实现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];
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
所以我尝试了宏无济于事:
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());
}
错误信息是
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
有没有办法在不剪切和粘贴每个初始化程序的情况下初始化这个数组?