I managed to distill my problem to this minimal uncompileable snippet:
struct MyStruct<D> {
x: D,
}
impl<D> MyStruct<D> {
fn new() -> Self {
let x: MaybeUninit<Self> = MaybeUninit::uninit();
// initialization is omitted for brevity
let y: Self = unsafe { std::mem::transmute(x) };
y
}
}
And I get the compiler error on std::mem::transmute
:
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
--> src/main.rs:97:32
|
97 | let y: Self = unsafe { std::mem::transmute(x) };
| ^^^^^^^^^^^^^^^^^^^
|
= note: source type: `MaybeUninit<MyStruct<D>>` (size can vary because of D)
= note: target type: `MyStruct<D>` (size can vary because of D)
Could anyone help me understand why D
size might vary, if all generic parameters are Sized
by default? And what can I change in code to make this work?
UPDATE: Obviously, I omitted the part where I initialize the initially uninitialized data. Also, I am aware about methods like assume_init
, but it does not help me in case when I need to create the fixed-sized array [MaybeUninit<MyStruct<D>>; K]
and after initialization - transmute it to [MyStruct<D>; K]
. While initial problem from my code sample can be resolved in other ways - I still am trying to understand what's wrong with the approach as it is.