Hi!
I am trying to initialize an array in const context with non-Copy items.
This compiles when the array has a length of 1 and fails for other lengths (including 0).
When the length is 0, the compiler complains that the item's destructor cannot be evaluated at compile time.
When the length is greater than 1, the compiler wants the item to be copyable.
Here a simplified example:
#[derive(Debug, Default, Clone)]
struct SomeStruct {
field: std::borrow::Cow<'static, str>,
}
impl SomeStruct {
const fn new() -> Self {
Self { field: std::borrow::Cow::Borrowed("") }
}
}
const DATA0: [SomeStruct; 1] = [SomeStruct::new(); 0];
const DATA1: [SomeStruct; 1] = [SomeStruct::new(); 1]; // This one compiles!
const DATA2: [SomeStruct; 2] = [SomeStruct::new(); 2];
I understand why the compiler rejects for length greater than 1. Not sure why it rejects the 0-length because it could simply not call SomeStruct::new() and avoids the destructor call issue.
Do you know some way of getting around these limitations?
II thought about using a combination of zero initialisation, ManuallyDrop and transmute_copy. However, this is quite complex, and I am afraid it could create memory leaks (although this is not so problematic because it is done at compile time).
Note that my real code is a bit more complex: The array length is computed using a const fn.