Rust : How to get sizeof::<T> in complie time or other way?

Viewed 940

I want to convert T to bytes array,

fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
    unimplemented!()
}

when I call this function let a = to_bytes::<u32>(); the type will be confirmed, but got error:

error[E0277]: the size for values of type `T` cannot be known at compilation time
   --> lab/test-bit/src/main.rs:3:56
    |
3   | fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
    |            - this type parameter needs to be `Sized`   ^ doesn't have a size known at compile-time
    |
1 Answers

Stable Rust does not support using generic parameters in const expressions.

In nightly, the code should work as long as you enable const_generics and const_evaluatable_checked.

In any case, you don't need the Sized bound, it is implicit.

Related