Compile errors by `transmute` and `PhantomData`

⚓ Rust    📅 2025-07-29    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 127 days ago. The information described in this article may have changed.

I am not good at English. Sorry if there are any funny expressions.


I must use transmute, unfortunately.
On top of that, I encountered an strange error.
I can't understand why this results in an error.

Test code

Compiling the following code ...

use std::{marker::PhantomData, mem};

fn conv<T, U1, U2>(src: MyType<T, U1>) -> MyType<T, U2> {
    unsafe { mem::transmute::<MyType<T, U1>, MyType<T, U2>>(src) }
}

#[repr(transparent)]
pub struct MyType<T, U> {
    fld1: T,
    fld2: PhantomData<U>,
}

... result in the following error.

error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> src\lib.rs:4:14
  |
4 |     unsafe { mem::transmute::<MyType<T, U1>, MyType<T, U2>>(src) }
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `MyType<T, U1>` (size can vary because of T)
  = note: target type: `MyType<T, U2>` (size can vary because of T)

My thought process

I know that transmute requires the input and output types to be the same size.

In this case, the input type is MyType<T, U1> and the output type is MyType<T, U2>. Here, the size difference between U1 and U2 can be ignored by PhantomData.

As an experiment, I removed the type fields and tried MyType<T> and MyType<T>, as well as MyType<U1> and MyType<U2>. Both compiled successfully. Is there a problem with combining normal types and PhantomData?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed