Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust : How to get sizeof::<T> at compile time or other way? [duplicate]

Tags:

sizeof

rust

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
    |
like image 493
Anunaki Avatar asked Sep 16 '25 14:09

Anunaki


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.

like image 120
Acorn Avatar answered Sep 18 '25 08:09

Acorn