Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I transmute a `MaybeUninit<T>` to a `T`?

I’d like to transmute a MaybeUninit<T> to a T.

use std::mem::transmute;
use std::mem::MaybeUninit;

fn make_init<T: Sized>(mt: MaybeUninit<T>) -> T {
    unsafe { transmute(mt) }
}

fn main() {
    make_init(MaybeUninit::new(1));
}

However this program gives me:

error[E0512]: cannot transmute between types of different sizes, or dependently-sized types

What’s the right way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Generally, the workaround when the compiler doesn’t know that types have the same size is to use transmute_copy(), but in your case there is MaybeUninit::assume_init() that does exactly what you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading