constant expression depends on a generic parameter this may fail depending on what value the parameter takes

Viewed 29

I want to use std::mem::transmute and std::mem::size_of using a generic parameter.

But Rust gives me the following error:

constant expression depends on a generic parameter this may fail depending on what value the parameter takes

here is a simplified version that should create a zeroed struct of type T and return it:

fn test<T>() -> T {
    let buf = [0u8; std::mem::size_of::<T>()];
    unsafe { std::mem::transmute(buf) }
}

How can I solve this problem? Do I have to add some kind of type constraint to T?

Note that this is just a simplified version of what I want to do, to create a zeroed struct you can use std::mem::zeroed() as @PitaJ noted

1 Answers

You can use std::mem::zeroed instead:

fn test<T>() -> T {
    // Only sound if zeroed is a valid representation of T
    unsafe { std::mem:zeroed() }
}
Related